mafortis
mafortis

Reputation: 7138

Laravel vue axios explanation needed

I'm trying to understand Vue and it's dependencies (newbie) just need help to understand the way axios works so it can be clear to me.

If I use code below it works to returning my data:

methods: {
            load: function() {
                axios.get('/api/projects')
                .then(
                    response => {
                        this.projects =  (response.data.projects);
                    }     
                )
                .catch(function (error) {
                    this.errors.push(error);
                    console.log(error);
                })
            }
        }

But if I use code below it doesn't return data:

methods: {
            load: function() {
                axios.get('/api/projects')
                .then(function (response) {
                    this.projects =  (response.data.projects);
                })
                .catch(function (error) {
                    this.errors.push(error);
                    console.log(error);
                })
            }
        }

The difference is in .then part only.

Upvotes: 1

Views: 126

Answers (2)

Tanmay
Tanmay

Reputation: 3169

From MDN:

An arrow function does not have its own this; the this value of the enclosing execution context is used.

It's not the axios that needs to be explained. It's how this keyword behaves in different contexts. Your first method makes use of something called Arrow Function, which doesn't have this of it's own so it uses the this of the current context. But your second method does have it's own this.

So, in order for you second method to work, you would have to cache this outside of the closure, like this:

methods: {
            load: function() {
                var that = this;
                axios.get('/api/projects')
                .then(function (response) {
                    that.projects =  (response.data.projects);
                })
                .catch(function (error) {
                    this.errors.push(error);
                    console.log(error);
                })
            }
        }

And then it will work.

Upvotes: 1

Orkhan Alikhanov
Orkhan Alikhanov

Reputation: 10060

this is referring to different object in both functions. Write console.log(this) and you will see that the one in arrow function is referring to Vue instance. The other one, however, is referring to other object. probably window. In the case of function() {} you can't access Vue instance via this. You need to store it beforehand in a variable.

var vm = this;
axios.get('/api/projects')
            .then(function (response) {
                console.log(this); // undefined or other object
                console.log(vm); // vue instance
                vm.projects =  (response.data.projects);
            })

See another SO post for more details.

Upvotes: 2

Related Questions