Recently, in the process of using vue, I used axios to make an interface request, but I found that the value could not be obtained, and the return was undefined.
show (item) { let searchText = item.keyword
console.log(this) // return the 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) // undefined if (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 all points to vue, but in axios, this points to axios , so you need to use arrow functions instead of this binding
show (item) { let searchText = item.keyword console.log(this) // 返回vue实例 axios.get('http://localhost:3000/search/multimatch?keywords=' + searchText, {}, {headers: {'Content-Type': 'application/x-www-form-urlencoded'}}) .then((res) => { console.log(this) // 返回vue实例 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 the vue instance
let that = this;
axios.get('http://localhost:3000/search/multimatch?keywords=' + searchText, {}, {headers: {'Content-Type': 'application/x-www-form-urlencoded'}})
.then((res) => { console.log(that) // return the 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) }) }