SoFunction
Updated on 2025-04-07

Detailed explanation of the pointing problem about this when vue uses axios

Preface

As we all know, axios is a plugin for Vue request data that appears after vue-resource. After vue was updated to 2.0, the author Youda announced that he would no longer update vue-resource, but instead recommended axios. For more detailed introductions, please refer to here:https:///article/

This article mainly introduces the pointing problem of this when using axios for vue. I won’t say much below, let’s take a look at the detailed introduction together.

1. Solution

When using axios for network requests in vue, you will encounter this that does not point to vue, but is undefined. You can use the arrow function "=>" to solve it. as follows:

methods: {
 loginAction(formName) {
 this.$('http://127.0.0.1/u/subLogin', {
  username: ,
  password: 
 })
  .then(function(response){
  (this); //Here this = undefined  })
  .catch((error)=> {
  (error); //Arrow function "=>" makes this point to vue  });

 });
 }
} 

2. Cause

The arrow function "=>" in ES6 is the lexical scope, determined by the context (that is, determined by the outer caller vue).

3. Off topic

Use the "=>" function to say goodbye to the previous two writing methods:

bind(this)To change this pointer of anonymous function

How to write hackvar _this= this;

loginAction(formName) {
 var _this= this;
 this.$("...")
 .then(function(response){
  (_this); //Here _this points to vue })
 });
 }

Summarize

The above is the entire content of this article. I hope that the content of this article has a certain reference value for everyone's study or work. If you have any questions, you can leave a message to communicate. Thank you for your support.