Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VueJS data property returns undefined in mounted function

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);
        })
    }
    
})
like image 213
Chris Wickham Avatar asked Dec 01 '22 14:12

Chris Wickham


1 Answers

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);
  })
}
like image 77
Phiter Avatar answered Dec 03 '22 04:12

Phiter