How to update vuejs component data after jquery calls when use turbolinks

断了今生、忘了曾经 提交于 2019-12-11 07:34:57

问题


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



来源:https://stackoverflow.com/questions/40959740/how-to-update-vuejs-component-data-after-jquery-calls-when-use-turbolinks

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!