一、 axios中this的指向問題
在vue中使用axios做網(wǎng)絡(luò)請(qǐng)求的時(shí)候,會(huì)遇到this不指向vue,而為undefined。
解決方法
1. 使用箭頭函數(shù) "=>"
"=>" 內(nèi)部的this是詞法作用域,由上下文確定(也就是由外層調(diào)用者vue來確定)。
methods: {
loginAction(formName) {
this.$axios.post("……")
.then(function(response){
console.log(this); //這里 this = undefined
})
.catch((error)=> {
console.log(this); //箭頭函數(shù)"=>"使this指向vue
});
});
}
}
1. 使用hack寫法
定義變量綁定this至vue對(duì)象。
methods: {
loginAction(formName) {
let _this = this;
this.$axios.post("……")
.then(function(response){
console.log(_this); //這里 _this 指向 vue
})
});
}
}