VueJS 数据属性在挂载的函数中返回未定义 [英] VueJS data property returns undefined in mounted function
问题描述
我使用 Axios 发出了一个 get 请求,它按预期返回了一些数据,但我无法在挂载的函数中访问应用程序的数据属性来分配请求的结果.this.productList
的控制台日志返回 undefined
.有人能指出我正确的方向吗?
I've made a get request using Axios which returns some data as expected, but I cannot access the app's data properties in the mounted function to assign the results of the request. The console log to this.productList
returns undefined
. Can anyone point me in the right direction?
new Vue({
el: '#products',
data: function(){
return{
test: 'Hello',
productList: null
}
},
mounted: function(){
axios.get('https://api.coindesk.com/v1/bpi/currentprice.json').then(function(response){
console.log(response.data);
console.log(this.productList)
}).catch(function(error){
console.log(error);
})
}
})
推荐答案
因为在那个函数中,this
不引用你的 vue 实例.它还有另一个含义.
Because in that function, this
doesn't refer to your vue instance. It has another meaning.
你可以在外层函数中创建一个临时变量来保存this
的值,像这样:
You can make a temporary variable to hold the value of this
in the outer function, like this:
mounted: function() {
let $vm = this;
axios.get('https://api.coindesk.com/v1/bpi/currentprice.json').then(function(response) {
console.log(response.data);
console.log($vm.productList)
}).catch(function(error) {
console.log(error);
})
}
或者你可以使用更好的箭头函数:
Or you can use the nicer arrow functions:
mounted: function() {
axios.get('https://api.coindesk.com/v1/bpi/currentprice.json').then((response) => {
console.log(response.data);
console.log(this.productList)
}).catch(function(error) {
console.log(error);
})
}
这篇关于VueJS 数据属性在挂载的函数中返回未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!