Home > Article > Web Front-end > Where does this point when vue uses axios?
This time I will show you where this points when vue uses axios, and what this does when using vue to call axiosWhat are the precautions. Here is a practical case, let's take a look.
Where does this point when vue uses axios
This article mainly introduces the problem of this pointing when Vue uses axios. I won’t say much below, let’s take a look at the detailed introduction.
1.Solution
When using axios to make network requests in vue, you will encounter that this does not point to vue, but is undefined. You can use the arrow function "=>" to solve the problem. 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. Reason
The internal this of the arrow function "=>" in ES6 is the lexical scope, which is determined by the context (that is, determined by the outer caller vue).
3. Digression
Using the "=>" function, you can say goodbye to the previous two ways of writing:
bind(this)
To change the this pointer of anonymous function
Hack writing method var _this= this;
:
loginAction(formName) { var _this= this; this.$axios.post("...") .then(function(response){ console.log(_this); //这里 _this 指向vue }) }); }
I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the PHP Chinese website!
Recommended reading:
How to download json format array to excel table with JS
How to operate jackson when parsing json string Letter case conversion
Angular validation function implementation steps
The above is the detailed content of Where does this point when vue uses axios?. For more information, please follow other related articles on the PHP Chinese website!