How to update vuejs component data after jquery ca

2019-07-22 12:16发布

问题:

I have a vuejs's component that after mounted should show data fetched from server and use response to update data. When I use turbolinks the vue js don't update the dom.

I tried many different ways to do that, but none worked =(, my last tried was this one:

Vue.component('pf-main-menu', {
  props: [''],
  template: '<pf-menu v-bind:links="links"></pf-menu>',
  data: function () {
    return { links: [{text: 'teste'}] }
  },
  mounted: function() {
    this.links = [{text: 'teste 2'}]; <-- This change works

    $.ajax({
      url: '/api/v1/menus/main_menu.json',
    }).success(function(res) {
      this.links = [{text: 'teste 3'}]; <-- This change does not work
    }.bind(this));
  }
});

https://gist.github.com/victorlcampos/a8c4f05ab53097e4ac07d5bf8306646e

I already tried this way too:

Vue.component('pf-main-menu', {
  props: [''],
  template: '<pf-menu v-bind:links="links"></pf-menu>',
  data: function () {
    return { links: [{text: 'teste'}] }
  },
  mounted: function() {
    this.links = [{text: 'teste 2'}];
    var self = this;

    $.ajax({
      url: '/api/v1/menus/main_menu.json',
    }).success(function(res) {
      self.links = [{text: 'teste 3'}];
    });
  }
});

回答1:

It is happening because your this is not pointing to correct scope, scope of this changes inside an $.ajax call, so you just have to do something like following:

  mounted: function() {
    this.links = [{text: 'teste 2'}]; <-- This change works
    var self = this
    $.ajax({
      url: '/api/v1/menus/main_menu.json',
    }).success(function(res) {
      self.links = [{text: 'teste 3'}]; <-- This change does not work
    }.bind(this));
  }
});

You can also check my similar answer here.



回答2:

According with Vue Docs you must use Vue.set to ensure reactive behavior.

    data: function () {
      return { 
        menu: {
          links: [ {text: 'teste'}] }
        }
     }, ....

In ajax sucess return:

    Vue.set(this.menu, links, [{text: 'teste 3'}] ); 

More Vue Docs