[Vuejs]-Unable to run for loop in vue js

-1👍

The problem is that you do not update the data array you specified for Vue.js. Instead you just create a new variable with the same name. That is not how it works.

Usually, you have to reference this.data. But as your scope (and thus, this) within the API callback is different, you have to make a reference to the correct this. E.g. using var vueThis = this;.

methods: {
    test: function() {
        var url = 'https://jsonplaceholder.typicode.com/posts';
        var apiCall = new XMLHttpRequest();
        var vueThis = this;
        apiCall.onload = function() {
            if(this.status == 200) {
                vueThis.data = JSON.parse(apiCall.responseText);
                console.log(vueThis.data);      
            }
            else {
                console.log("Unable to load data, Please try later!!!!");
            }
        }

        apiCall.open("GET", url, true);
        apiCall.send();
    }
}
👤str

Leave a comment