How to write data from an AJAX request to DATA in VUE JS?

Tell me please, how in DATA to write data from the AJAX response? Example:

var example = new Vue({
    el: '#example',
    data:{
        myArr: []
    },
    created: function () {
        $.getJSON('data.json', function(data) {
            this.myArr = data;
        });
    }
  });

The problem is that in myArr, the response data is not written. How to solve this? Thank you.

Upvotes: 1

Views: 507

Answers (1)

Mihir Bhende
Mihir Bhende

Reputation: 9045

Can you try this ? Basically this inside the ajax is not exactly the one you would expect.

var example = new Vue({
    el: '#example',
    data:{
        myArr: []
    },
    created: function () {
        var vm = this;
        $.getJSON('data.json', function(data) {
            vm.myArr = data;
        });
    }
  });

You can also use reactivity setting method $set instead of directly assigning to the vm.myArr : https://v2.vuejs.org/v2/guide/reactivity.html

Upvotes: 3

Related Questions