【问题标题】:How to update vuejs component data after jquery calls when use turbolinks使用turbolinks时jquery调用后如何更新vuejs组件数据
【发布时间】:2016-12-04 14:38:44
【问题描述】:

我有一个 vuejs 的组件,它在安装后应该显示从服务器获取的数据并使用响应来更新数据。当我使用 turbolinks 时,vue js 不会更新 dom。

我尝试了许多不同的方法来做到这一点,但都没有奏效 =(,我最后一次尝试的是这个:

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

这个方法我也试过了:

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'}];
    });
  }
});

【问题讨论】:

    标签: javascript jquery ajax turbolinks vuejs2


    【解决方案1】:

    发生这种情况是因为您的 this 没有指向正确的范围, this 的范围在 $.ajax 调用中发生了变化,因此您只需执行以下操作:

      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));
      }
    });
    

    您也可以查看我的类似答案here

    【讨论】:

    • 我更新了问题,我之前试过你的方法=(。谢谢回答
    • 我现在发现问题与turbolinks有关
    【解决方案2】:

    根据 Vue Docs,您必须使用 Vue.set 来确保反应行为。

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

    在ajax成功返回:

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

    更多Vue Docs

    【讨论】:

      猜你喜欢
      • 2019-03-20
      • 2017-03-06
      • 2017-11-18
      • 1970-01-01
      • 2021-08-12
      • 2018-08-02
      • 2017-11-30
      • 2018-05-16
      • 1970-01-01
      相关资源
      最近更新 更多