VUE使用axios數據請求時報錯 TypeError: Cannot set property 'xxxx' of undefined 的解決辦法


正常定義全局變量:

data:function (){
      return{
        currentOrders:[]
      }
    },

  使用Axios發送請求並獲取后端數據時,如果在then中使用this.currentOrders會出現TypeError: Cannot set property 'xxxx' of undefined錯誤。

  原因是使用this$axios().then(function(response){}).catch()格式獲取參數,then的內部 this 沒有被綁定,所以不能使用Vue的實例化的this。

  解決辦法一:在this.$axios外部將this賦值為自定義變量:var that = this,然后在then里面使用that.currentOrders

var that = this
      this.$axios({
        method: 'get',
        url: 'xxxxxx',
      }).then(function (response) {
        var jsonObj = JSON.parse(JSON.stringify(response.data))
        if (jsonObj.code === ERR_ok){
          that.currentOrders = jsonObj.data
        }
      }).catch(function (error) {
        console.log(error);
      })

第二種方法:用ES6箭頭函數,箭頭方法可以和父方法共享變量

this.$axios({
        method: 'get',
        url: 'xxxxxx',
      }).then((response)=>{})
      .catch(){}
 

  


免責聲明!

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



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