在vuejs 中使用axios不能获取属性data的解决方法

axios中的this.labels,未被定义

data(){
        return {
            labels: null,
        }
    },
fetchData() {
      axios.get('/static/api/form.json')
      .then(function (response) {
        this.labels = response.data
        console.log("axios=="+ JSON.stringify(response.data));
      })
      .catch(function (error) {
        console.log("axios=="+error);
      });
    },
created () {
    this.fetchData()
   // this.getFormJson()
  },

 

谷歌报错:

axios==TypeError: Cannot set property 'labels' of undefined

解答

出错问题:
then 这个里边的赋值方法this.followed = response.data.followed会出现报错,什么原因呢?在Google上查了下,原来是在 then的内部不能使用Vue的实例化的this, 因为在内部 this 没有被绑定。
可以看下 Stackoverflow 的解释:

In option functions like data and created, vue binds this to the view-model instance for us, so we can use this.followed, but in the function inside thenthis is not bound.

So you need to preserve the view-model like (created means the component's data structure is assembled, which is enough here, mounted will delay the operation more):

 

解决方法

fetchData() {
      var self = this ;
      axios.get('/static/api/form.json')
      .then(function (response) {
        self.labels = response.data
        console.log("axios=="+ JSON.stringify(response.data));
      })
      .catch(function (error) {
        console.log("axios=="+error);
      });
    },

或者我们可以使用 ES6 的 箭头函数arrow function,箭头方法可以和父方法共享变量 :

axios.get('/static/api/form.json')
      .then((response) =>{
        this.labels = response.data
        console.log("axios=="+ JSON.stringify(response.data));
      })
      .catch((error)=> {
        console.log("axios=="+error);
      });

 

axios=={"credit-bankcard-validate-2keys":[{"label":"姓名","prop":"name","rule":"正则"},{"label":"银行卡号","prop":"bankNo","rule":"正则"}],"credit-bankcard-validate-3keys":[{"label":"姓名","prop":"name","rule":"正则"},{"label":"银行卡号","prop":"bankNo","rule":"正则"},{"label":"身份证号","prop":"idCard","rule":"正则"}],"credit-bankcard-validate-4keys":[{"label":"姓名","prop":"name","rule":"正则"},{"label":"银行卡号","prop":"bankNo","rule":"正则"},{"label":"身份证号","prop":"idCard","rule":"正则"},{"label":"手机号码","prop":"phoneNo","rule":"正则"}]}

 

posted @ 2018-01-15 10:23  JennyGao  阅读(3429)  评论(1编辑  收藏  举报