VueJS data property returns undefined in mounted function

吃可爱长大的小学妹 提交于 2019-12-13 03:14:56

问题


I'm about an hour removed from starting to learn VueJS. 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);
    })
}

})

回答1:


Because in that function, this doesn't refer to your vue instance. It has another meaning.

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);
  })
}


来源:https://stackoverflow.com/questions/51929737/vuejs-data-property-returns-undefined-in-mounted-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!