Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DOM not updating after AJAX data update in VueJS

I'm using Vue.js to modify my DOM. I'm triggering the fetch_data() method which trying to update data.messages to read 'Love the Vue.JS' after the successful completion of the AJAX call.

The AJAX call is working successfully and it does indeed update data.message in this line:

self.message = 'Love the Vue.JS'

I can see it works because it prints in the console. The problem is that the DOM is not updating with the new definition of data.message. How do I get this to work and update the DOM when the data is updated?

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>
like image 335
user3308477 Avatar asked May 29 '18 17:05

user3308477


1 Answers

The problem is that your this context gets lost when you call out to jQuery. The callback method you have (success: function) doesn't have a reference back to Vue. The way to pass the correct context is, conveniently enough, the context property in your $.ajax call.

It's all documented at the jQuery site: https://api.jquery.com/jQuery.ajax/ - just search for the word "context" and you'll find it.

Your improved ajax call should look something like this:

$.ajax({
  url: '/test_json',
  context: this,
//  [... etc ...]
  success: function(data) {
    this.message = "reference to Vue data message";
  }
);
like image 98
Nathan Strutz Avatar answered Oct 02 '22 06:10

Nathan Strutz