javascript - VueJS 中的 AJAX 数据更新后 DOM 未更新
问题描述
我正在使用 Vue.js 来修改我的 DOM。在成功完成 AJAX 调用后,我正在触发fetch_data()
尝试更新以读取“Love the Vue.JS”的方法。data.messages
AJAX 调用工作成功,并且确实data.message
在这一行中更新:
self.message = 'Love the Vue.JS'
我可以看到它有效,因为它在控制台中打印。问题是 DOM 没有使用data.message
. 当数据更新时,如何让它工作并更新 DOM?
var app = new Vue({
delimiters: ['[[', ']]'],
el: '#app',
data: { message: 'Hello Vue.js!' },
methods: {
fetch_data: function() {
console.log('Running script for ajax...');
$("#retrieve_data_wait").text("Retrieving data. This will update when complete...");
$.ajax({
url: '/test_json',
dataType: 'json',
timeout: 60000,
success: function(data) {
$("#retrieve_data_wait").text(data.test);
self.message = 'Love the Vue.JS';
console.log('SUCCESS')
console.log(self.message);
},
error: function(data) {
$("#retrieve_data_wait").text("Fail");
}
// error: function(jqXHR, status, errorThrown) {
// //the status returned will be "timeout"
// alert('Got an error (or reached time out) for data generation. Please refresh page and try again. If you see this more than once, please contact your customer success agent.');
// }
});
}
}
})
<div id="app">
<span id="retrieve_data_wait"></span>
</div>
解决方案
问题是this
当你调用 jQuery 时你的上下文会丢失。您拥有的回调方法 ( success: function
) 没有对 Vue 的引用。传递正确上下文的方法很方便,就是调用context
中的属性。$.ajax
这一切都记录在 jQuery 站点:https ://api.jquery.com/jQuery.ajax/ - 只需搜索单词“context”,您就会找到它。
您改进的 ajax 调用应如下所示:
$.ajax({
url: '/test_json',
context: this,
// [... etc ...]
success: function(data) {
this.message = "reference to Vue data message";
}
);
推荐阅读
- ios - 找不到 Plugin.h 文件:flutter 和 xcode
- android - RecyclerView 水平布局上的选定项目隐藏在 Android 上的布局开始之后
- bash - 如何传递标志以外的其他参数
- javascript - 如何正确使用 UseCallback Hook
- java - 在多个方法中使用数组
- function - Flutter switch 小部件-我只希望它在它处于活动状态时执行该功能,该怎么办?
- swift - SwiftUI:无法在此文件中预览 - *.app 可能已崩溃..但构建良好
- r - 用指数估计填空
- spring - springboot 应用程序中 gradle bootrun 和 bootjar/build 的区别
- python - xarray 中是否有用于从数据集中删除异常值的内置函数?