levis
levis

Reputation: 472

When i set axios response in vue js i get an empty array in laravel blade

I am trying to display results in my page, When i log response. I can see the response, I have tried passing the response to vue js data, but each time it displays an empty array

     var app = new Vue({
        el: '#app',
        data: {
            results: []
        },
        mounted(){
            var url = "{{ url('fetch/messages') }}";
            axios.get(url)
                .then(function (response) {
                    console.log(response.data);
                    this.results = response.data;
                })
                .catch(function (error) {
                    console.log(error);
                });
        }

I am trying to display the response in the page @{{ results }}

Upvotes: 0

Views: 856

Answers (2)

Rwd
Rwd

Reputation: 35200

The reason your data is not getting added to the Vue instance is because this will not refer to the Vue instance inside a closure (traditional function () {}). Please have a look at this article for more information on scope and this keyword in javascript.

Below I refer to ES quite a bit which stands for ECMAScript. Here is an article to show the difference between it and vanilla javascript.

I can see from your post that you're using ES6/ES2015 syntax for your method definitions so I'm assuming you're happy with just using modern browsers for now.

If this is the case then you can use Arrow Functions to get past the scope issue:

.then(response => {
    console.log(response.data);
    this.results = response.data;
})

If not, then as mentioned in the scope article above, you would need to assign this to a variable:

var self = this;

axios.get(url)
    .then(function (response) {
        console.log(response.data);
        self.results = response.data;
    });

If this is the case, then I would also suggest not using the ES6 method definitions either so change mounted(){ to mounted: function () {.


Finally, if you want to be able to use modern/new javascript e.g. ES6/ES2015 and above, but have your code work consistently with older browsers then I would suggest using something like Laravel mix to compile your javascript for you.

Laravel Mix Documentation Laravel Mix tutorial series

Upvotes: 2

Polaris
Polaris

Reputation: 1249

You cannot have the following line of code, it will break.

            var url = "{{ url('fetch/messages') }}";

Upvotes: 0

Related Questions