Vue uses Axios this to point to the problem

Source: Internet
Author: User

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:

    1. Bind (this) to change the anonymous function of this point
    2. 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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.