Scope of variable issue


#1

hi, i’m new in vue js, here is a bit of code:

var app = new Vue({
  el: '#app',
  
  data : {
    users : [],
  },
  
  methods : {
    getUsers(){
        axios.get('http://0.0.0.0:8080/api/users').then(function(response){
            this.users = response.data.users;
        }).catch(error => {
        console.log(error);
        })
    }
  },
  
})

this does not works, the variable users is not updated. But, if i write app.users instead of this.users, it works. I don’t get it, in a lot of example people use this.variable inside .then function.


#2

These people usualy use an arrow function instead of a normal one, though:

axios.get('http://0.0.0.0:8080/api/users').then((response) => {

this in arrow functions always refers to the current scope, which is why this works. in normal functions, this is usually undefined unless used as a method in an object.

You seem not to fully understand how this works in Javascript. It’s one of the key things to understand about the language though, so I strongly recommend to read up on it.


#3

thanks, now in make sense.