1

I am making simple ajax call with vuejs and axios:

var app1 = new Vue({
  el: '#app1',
  data: {
    test: []
  },
  methods: {    
    setAJAX: function () {
      axios.get('/Departments/GetDepartments/').then(response => this.test = response.data.listBACAET);
    }
  }
});

Why is this working:

setAJAX: function () {
      axios.get('/Departments/GetDepartments/').then(response => this.test = response.data.listBACAET);
    }

But this is not working, changes are not mapped into table (this.test is undefined):

setAJAX: function () {
      axios.get('/Departments/GetDepartments/').then(function(response){this.test = response.data.listBACAET});
    }
1
  • how is setAJAX being called? Commented Nov 25, 2019 at 10:04

1 Answer 1

4

This is because of the way arrow functions work: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions#No_separate_this

When using an arrow function, this is implicitly bound to this of the enclosing scope, which is, in your case, the vue instance on which the method is called. So you're setting the data of your view model, which works.

When using a std. function, there is no this in the scope, hence the error. To use a std. function, you need to define a closure for your view model like this:

setAJAX: function () {
  let vm = this
  axios.get('...').then( function(response) {
    vm.test = response.data.listBACAET
  });
}
Sign up to request clarification or add additional context in comments.

1 Comment

There is only one thing I don't understand - axios is function (typeof axios == 'function'). How can this call be made: axios.get('...') ? It seems like function inside function.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.