javascript - How to save data in Vue instance
问题描述
The question is quite simple, All I want is to get the data after the AJAX post saved in Vue instace's data. Here is my code:
const VMList = new Vue({
el: '#MODAL_USER_DATA',
data: {
user: []//,
//userAcc: []
},
methods: {
getUserAcc: function ( userID ) {
this.user = { _id : userID };
var self = this
$.ajax({
url: "/listuser",
type: "POST",
data: this.user,
success: function(data) {
this.user = data ;
//this.userAcc = Object.assign({}, this.userAcc, data );
alert(JSON.stringify(this.user));//show the user correctly (e.g user = data)
$('#popupDeleteModal').modal('show');
alert(JSON.stringify(data));//show data,the entire json object,everything is good
},
error: function(err) {
console.log('error: ',err);
},
});
}
}
});
And after I trigger the getUserAcc(id) method,I try to verify the VMList.user value in browser console,and I get only the id.Seems like after the function is over the data is reset.How could I store the data from the AJAX post request in the user object from data:{...} ?
Thank you for help!!!
解决方案
问题是this
在你的 ajax 返回函数内部不再引用 vue 实例。
解决方案是将this
关键字保存到函数内部的变量中。例子:
getUserAcc: function ( userID ) {
var that = this;
this.user = { _id : userID };
$.ajax({
url: "/listuser",
type: "POST",
data: this.user,
success: function(data) {
that.user = data;
//Rest of your code
},
error: function(err) {
console.log('error: ',err);
},
});
}
以下是有关关键字行为的更多信息this
:https ://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this
推荐阅读
- android - “crashlytics 应用初始化程序禁用”是什么意思?
- javascript - 等待谷歌地图方向服务时禁用按钮
- c - 如何比较两个数学库实现?
- mongodb - 在 mongodb 中查找指定大小的句子的第一个单词
- unix - 在 Unix csh 脚本中获取昨天的日期
- google-compute-engine - 为什么从谷歌云快照恢复的虚拟机在其数据库中没有数据?
- java - Windows 和 Linux 之间的 Weblogic Xquery 异常区别
- google-sheets-api - 如何在 Googlesheet IMPORTXML 函数中获取 Xpath 查询?
- unity3d - Unity 将顶点添加到原始网格中
- html - 如何在 Markdown 文件中添加 GIF 控件