javascript - 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() 函数,但我仍然得到这是未定义的错误
解决方案
您在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();
}
}
推荐阅读
- google-cloud-platform - 负载平衡托管实例组的集中式日志存储
- javascript - Webpack 从同构组件延迟加载模块(服务器和客户端之间的共享代码)
- mosquitto - 如何禁止或保留 mosquitto 经纪人中的主题?
- ssm - Confd 忽略了我的 aws 配置中设置的角色?
- javascript - 如何使用 React 在emotionjs 中组合样式组件?
- laravel - 在 GET 中或在 Laravel 中渲染视图时获取登录尝试次数
- javascript - 使用 Webpack 和 Mustache 渲染与主应用程序无关的多个页面
- python - 用于自定义图像大小的 MobileNets
- c# - 如何使用 C# 和 ASP.Net Core 2.2 连接和收听外部 websocket url
- android - 如何从 AOSP 源中获取可构建的 android 应用程序