English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Preface
As everyone knows, axios is a vue-resource after the appearance of Vue data request plugins. Vue has been updated to2.0, the author Youda announced that he would no longer support vue-resource updates, but recommends axios. For more detailed information, please refer to here: https://www.oldtoolbag.com/article/109444.htm
This article mainly introduces the problem of this pointer when using axios in vue. Without further ado, let's take a detailed look at the introduction together.
1.Solution
When using axios for network requests in vue, you may encounter the issue that this does not point to vue but is undefined. You can solve this problem by using arrow functions "=>". 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); //Here this = undefined }); .catch((error)=> { console.log(error); //The arrow function "=>" makes this point to vue }); }); } }
2. Reason
ES6The arrow function "=>" inside is lexical scope, determined by the context (that is, determined by the outer caller vue).
3. Off-topic
Using the "=>" function, you can say goodbye to the two previous writing methods:
bind(this) to change the this pointer of the anonymous function
hack writing var _this= this; :
loginAction(formName) { var _this= this; this.$axios.post("...") .then(function(response){ console.log(_this); //Here _this points to vue }); }); }
Summary
That's all for this article. I hope the content of this article is of certain reference value to everyone's learning or work. If you have any questions, you can leave messages for communication. Thank you for your support of the呐喊 tutorial.
Declaration: The content of this article is from the Internet, and the copyright belongs to the original author. The content is contributed and uploaded by Internet users spontaneously. This website does not own the copyright, has not been manually edited, and does not assume relevant legal liability. If you find any content suspected of copyright infringement, please send an email to: notice#oldtoolbag.com (Please replace # with @ when sending an email to report abuse, and provide relevant evidence. Once verified, this site will immediately delete the infringing content.)