Mule
Mule

Reputation: 868

Cannot access Vue data set within mounted via ajax

I am using Vue2. I am getting json data via ajax in my mounted method. I then set that data to a data variable expecting to be able to access it from other methods outside of mounted, but all I get is an empty observable.

Any suggestions/advice? Thanks for the help.

var vm = new Vue({
el: '#app',
data: function () {
    return {
        allJson: []
    };
},
methods: {
    updateTableData:  function(isActive) {
        // cannot access this.allJson here
    }
},
mounted: function() {
    $.getJSON(Routes.USERS_GET_JSON, function(json) {
        this.allJson = json;
    });
}

});

Upvotes: 0

Views: 430

Answers (2)

Ohgodwhy
Ohgodwhy

Reputation: 50767

I haven't used jQuery in a long, long time, but if I remember correctly you need to explicitly declare the context of this if you wish to use it within the callback, else you get something unexpected. However, I don't know if $.getJSON supports it even though it's a wrapper. So you can try the following:

$.getJSON(Routes.USERS_GET_JSON, function(json) {
    this.allJson = json;
}, {
    context: this
})

Or you can use .bind off of the function to scope this

$.getJSON(Routes.USERS_GET_JSON, function(json) {
    this.allJson = json
}.bind(this))

Or if you're tranpsiling down with babel (which you probably are) you can use fat arrow syntax:

$.getJSON(Routes.USERS_GET_JSON)
    .done( (json) => {
        this.allJson = json
    })

Or you can just alias this before the $.getJSON

let _self = this

 $.getJSON(Routes.USERS_GET_JSON, function(json) {
    _self.allJson = json
 })

Upvotes: 2

Husam Elbashir
Husam Elbashir

Reputation: 7177

My guess is that this is not bound to your vue instance inside the callback function. Try the following

var vm = new Vue({
el: '#app',
data: function () {
    return {
        allJson: []
    };
},
methods: {
    updateTableData:  function(isActive) {
        // cannot access this.allJson here
    }
},
mounted: function() {
    const self = this;
    $.getJSON(Routes.USERS_GET_JSON, function(json) {
        self.allJson = json;
    });
}
});

Upvotes: 1

Related Questions