1

i have started working on a small project using VueJs, i've made a get request using Axios library which returns some data as expected, but I cannot call loadUsers function using this inside mounted this is my code:

export default{
  data(){
     return {
        users : {}
     }
  },
  methods:{
     addCustomer(){
        //var form = document.querySelector('#add-customer');
        var formData = $('#add-customer').serialize();
        axios.post('/Thirdparty', formData).then(function(response){
           helper.validation(response.data);
           //alert(response.data.error);
        });
     },
     loadUsers(){
        axios.get('/Thirdparty/loadUsers').then(function(data){
           this.users = data.data;
        });
     }
  },
  created(){
     let self=this
     self.loadUsers(); 
  }
}

as you can see also i've used self variable to call my loadUsers() function, but i'm still getting this is undefined error

Amine Bouhaddi
  • 554
  • 1
  • 7
  • 24
  • You need to do `let self=this;` in `loadUsers()` before doing the axios call, not in `created()`. – connexo Nov 13 '19 at 23:52

1 Answers1

2

You're referencing this.users within the callback to axios.get().then() in loadUsers(). Due to you're using a standard function and not an arrow function, this is not referring to the Vue instance, i.e. the scope for this is now incorrect. Either use an arrow function or change the reference:

// Do this...
export default{
  data(){
     return {
        users : {}
     }
  },
  methods:{
     addCustomer(){
        //var form = document.querySelector('#add-customer');
        var formData = $('#add-customer').serialize();
        axios.post('/Thirdparty', formData).then(function(response){
           helper.validation(response.data);
           //alert(response.data.error);
        });
     },
     loadUsers(){
        axios.get('/Thirdparty/loadUsers').then((data) => { // Using an arrow function.
           this.users = data.data;
        });
     }
  },
  created(){
     let self=this
     self.loadUsers(); 
  }
}

// Or this...
export default{
  data(){
     return {
        users : {}
     }
  },
  methods:{
     addCustomer(){
        //var form = document.querySelector('#add-customer');
        var formData = $('#add-customer').serialize();
        axios.post('/Thirdparty', formData).then(function(response){
           helper.validation(response.data);
           //alert(response.data.error);
        });
     },
     loadUsers(){
        let self=this; // Adding "self"
        axios.get('/Thirdparty/loadUsers').then(function(data){
           self.users = data.data; // Referencing "self" instead of "this".
        });
     }
  },
  created(){
     let self=this
     self.loadUsers(); 
  }
}
B. Fleming
  • 7,170
  • 1
  • 18
  • 36