1.解決辦法
在vue中使用axios做網絡請求的時候,會遇到this不指向vue,而爲undefined,可以使用箭頭函數"=>"來解決。如下:
methods: {
loginAction(formName) {
this.$axios.post('http://127.0.0.1/u/subLogin', {
username: this.username,
password: this.password
})
.then(function(response){
console.log(this); //這裏 this = undefined
})
.catch((error)=> {
console.log(error); //箭頭函數"=>"使this指向vue
});
});
}
}
2. 原因
ES6中的 箭頭函數 "=>" 內部的this是詞法作用域,由上下文確定(也就是由外層調用者vue來確定)。
3. 題外話
使用"=>"函數,就可以告別之前的兩種寫法了:
- bind(this)來改變匿名函數的this指向
- hack寫法
var _this= this;
:loginAction(formName) { var _this= this; this.$axios.post("...") .then(function(response){ console.log(_this); //這裏 _this 指向vue }) }); }