首页 > 解决方案 > 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>

标签: javascriptajaxvue.js

解决方案


问题是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";
  }
);

推荐阅读