vue数据请求

一、使用vue-resource模块请求数据,官方不在更新

1、在终端上执行  $ cnpm install --save vue-resource   下载 vue-resource 模块

2、

import VueResource from 'vue-resource'    // 导入vue-resource模块

 

3、

Vue.use(VueResource)        //使用模块

 

4、发起网路请求的代码放在钩子函数中

     

export default {
             name: "global",
             data () {
                   return {
                           // 请求的地址
                           url:"./././static/******.json"// 建立一个数组去接受请求回来的数据,方便使用
                           list:[],
                   };
              },


            // 在钩子函数中发起请求
            created(){
                         this.$http.get(this.url).then(res=>{
                                        // 在控制台中打印出请求的数据
                                        console.log(res.data);
                                        //创建的数组去承载请求回来的数据
                                        this.list = res.data.**;
                              },err=>{
                                     console.log(err);
                         });
             }
      }

 

二、使用axios去请求数据,非官方提供的,建议使用
1、$ cnpm install --save axios 下载axios模块
 
2、/导入axios模块
           
   import axios from 'axios'   //导入模块

 

3、注册axios,由于axios是非官方的模块无法使用Vue.use()方法来注册,只能在原型上注册
     
     Vue.prototype.axios =axios   //在原型链上增加属性后面才可以使用
     export default {
              name: "global",
             data () {
                   return {
                           // 请求的地址
                           url:"./././static/******.json",
                          // 建立一个数组去接受请求回来的数据,方便使用
                           list:[],
                   };
              },
            // 在钩子函数中发起请求
            created(){
                         this.axios.get(this.url).then(res=>{
                                       //  在控制台中打印出请求的数据 
                                        console.log(res.data);
                                       // 创建的数组去承载请求回来的数据
                                        this.list = res.data.**;
                              },err=>{
                                     console.log(err);
                         });
             }
      }

 

posted @ 2017-10-25 21:15  不乱来的嫖客  阅读(1583)  评论(0编辑  收藏  举报