正常定義全局變量:
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(){}