This point problem in Axios

Source: Internet
Author: User

Recently, in using the Vue process, the interface request was made using Axios, and the value was not found and returned as undefined.

Show (item) {Let SearchText=Item.keyword
Console.log (this)//return to Vue instance Axios.get (' http://localhost:3000/search/multimatch?keywords= ' + SearchText, {}, {headers: {' content-type ': ' application/ X-www-form-urlencoded '}}). Then (function (res){Console.log ( this)//undefinedif(Res.data.code = = 200) { This. Artistdata = res.data.result.artist[0] This. Albumdata = res.data.result.album[0] } }) .Catch(ERR) ={Console.log (err)})
}

In Vue, this points to Vue, but in Axios, this points to Axios, so you need to use the arrow function without binding the This

Show (item) {Let SearchText=Item.keyword Console.log ( This)//return to Vue instanceAxios.get (' http://localhost:3000/search/multimatch?keywords= ' + SearchText, {}, {headers: {' Content-type ': ' Application/x-www-form-urlencoded '}}). Then (RES)={Console.log ( This)//return to Vue instance         if(Res.data.code = = 200) { This. Artistdata = res.data.result.artist[0] This. Albumdata = res.data.result.album[0]         }       })       .Catch(ERR) ={Console.log (ERR)})}
or assign the value of this to an internal variable
Show (item) {Let   searchtext = Item.keyword Console.log (this)//return Vue instance
let is = this; Axios.get (' http://localhost:3000/search/multimatch?keywords= ' + SearchText, {}, {headers: {' Content-type ': ' Application/x-www-form-urlencoded '}}) . Then (res) = { console.log (that)//return to Vue instance C12/>if (Res.data.code = =) { this.artistdata = res.data.result.artist[0] This.albumdata = Res.data. Result.album[0]}). catch ((Err) = {Console.log (ERR)})}

This in Axios points to the problem

Related Article

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.