1. Workaround
When using Axios in Vue for network requests, you will encounter this not pointing to Vue, but for undefined, you can use the arrow function "= =" to resolve. As follows:
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. Causes
The "=" inside of the arrow function in ES6 is the lexical scope, determined by the context (that is, by the outer caller vue).
3. Off-Topic
By using the "= =" function, you can say goodbye to the previous two types of notation:
- Bind (this) to change the anonymous function of this point
- Hack notation
var _this= this; : loginAction(formName) { var _this= this; this.$axios.post("...") .then(function(response){ console.log(_this); //这里 _this 指向vue }) }); }
Vue uses Axios this to point to the problem