我正在使用 Vue.js 修改我的 DOM。我正在触发 fetch_data()
方法,该方法试图在成功完成 AJAX 调用后更新 data.messages
以读取“Love the Vue.JS”。
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>
最佳答案
问题是当您调用 jQuery 时,您的 this
上下文丢失了。您拥有的回调方法 (success: function
) 没有对 Vue 的引用。传递正确上下文的方法很方便,就是 $.ajax
调用中的 context
属性。
这一切都记录在 jQuery 站点:https://api.jquery.com/jQuery.ajax/ - 只需搜索“上下文”一词,您就会找到它。
改进后的 ajax 调用应如下所示:
$.ajax({
url: '/test_json',
context: this,
// [... etc ...]
success: function(data) {
this.message = "reference to Vue data message";
}
);
关于javascript - VueJS 中的 AJAX 数据更新后 DOM 不更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50589650/