亮宝前端学习室

Vue笔记 路由及数据请求

2017-05-10  本文已影响532人  路路有话说

路由 需要安装 路由的插件
数据请求心好累,一直请求不到 后来发现没引入 一定要记得引入
这里先做路由在做 数据请求

先做对应的安装

npm install  vue-router vue-resource --save-dev

对应的页面代码

import VueRouter from 'vue-router';
import VueResource from "vue-resource"
Vue.use(VueRouter);
Vue.use(VueResource);
//使用
const routerConfig = new VueRouter({
    routes:[
        { path: '/', component: news_list },
        { path: '/news', component: news_list },
        { path: '/news/:newsid', component: newsdetail,name:"newsdetail"},
        { path: '/login', component: loginView }
    ]
})

Vue.component('user-nav', user_nav)
let myvue=new Vue({
    el:".container",
    router:routerConfig,
    mounted(){
  this.$http.get("请求地址")
                    .then(function(res){
                      console.log(res.body)
                    },function(rs){})
     },});

说明

路由使用文档 在这里

启动路由

const routerConfig = new VueRouter({
    routes:[
        { path: '/', component: news_list },
        { path: '/news', component: news_list },
        { path: '/news/:newsid', component: newsdetail,name:"newsdetail"},
        { path: '/login', component: loginView }
    ]
})
const router = new VueRouter({ //初始化router
    routes:routesConfig
})
const myvue= new Vue({
    el:".container",
    router
});

设置头部-单独注册一个头组件

Vue.component("page-nav",pagenav);

数据请求使用文档在这里

文档中有一行奇怪的实例

this.$http.get('/someUrl', [options]).then(successCallback, errorCallback);

someUrl 表示 请求地址
options 请求的参数
successCallback 请求成功的回调方法
errorCallback 请求失败的回调方法
我在上面就直接使用了function(rs){}
其中 rs 表示返回的值 可以直接拿来调用 ,这点上面的文档中有说明

需要注意的是 这里请求需要做跨域处理

在你的PHP端加入
// 指定允许其他域名访问  
header('Access-Control-Allow-Origin:*');   //允许所有
// 响应类型  
header('Access-Control-Allow-Methods:GET,POST');  
// 响应头设置  
header('Access-Control-Allow-Headers:x-requested-with,content-type'); 

获取参数 假设我们的 url 是 http://localhost:8080/#/news/4
这里4 表示新闻的 id 可以使用
this.$route.params.newsid 获取到这个 4
对应在列表页中 a 标签 使用 <router-link :to="{name:'newsdetail', params:{ newsid: news.newsid}}"> 来替代
同样的文档 在这里
对应的照抄就行了

上一篇 下一篇

猜你喜欢

热点阅读