在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":"正則"}]}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM