首页 > 解决方案 > VueJS 在创建的函数中返回未定义

问题描述

我已经开始使用 VueJs 开展一个小项目,我已经使用 Axios 库发出了一个获取请求,该库按预期返回了一些数据,但是我无法使用这个内部安装的 loadUsers 函数调用这是我的代码:

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(); 
  }
}

正如您所看到的,我也使用 self 变量来调用我的 loadUsers() 函数,但我仍然得到这是未定义的错误

标签: javascriptvue.jsaxios

解决方案


您在this.users回调中引用axios.get().then()in loadUsers()。由于您使用的是标准函数而不是箭头函数,this因此不是指 Vue 实例,即this现在的范围不正确。使用箭头函数或更改参考:

// 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(); 
  }
}

推荐阅读