最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - VueJS data property returns undefined in mounted function - Stack Overflow

programmeradmin2浏览0评论

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('.json').then(function(response){
            console.log(response.data);
            console.log(this.productList)
        }).catch(function(error){
            console.log(error);
        })
    }
    
})

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);
        })
    }
    
})
Share Improve this question edited Jul 19, 2020 at 18:36 Phiter 15k14 gold badges51 silver badges85 bronze badges asked Aug 20, 2018 at 11:24 Chris WickhamChris Wickham 5212 gold badges5 silver badges20 bronze badges 1
  • Possible duplicate of How to access the correct `this` inside a callback? – t.niese Commented Aug 20, 2018 at 11:25
Add a comment  | 

1 Answer 1

Reset to default 21

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

发布评论

评论列表(0)

  1. 暂无评论