【问题标题】:Vue.js event to fire after data is updated数据更新后触发 Vue.js 事件
【发布时间】:2016-04-15 23:13:25
【问题描述】:

我有一个 Vue.js 应用程序,其中有几个组件用于处理一些重复性任务。

我也在从 AJAX 请求中获取数据。

我想要输入的是,在 Vue 数据(treeDataflatTreeData)更新并采取行动后是否有事件触发,以便我可以执行任何其他操作?

var app = new Vue({
    el: 'body',
    data: {
        treeData: {items: {}},
        flatTreeData: [],
    },
});

$.getJSON('./paths.json').done(function(data) {

    // apply the file structure to the vue app
    demo.treeData = data;

    demo.flatTreeData = flattenTree(data);

});

【问题讨论】:

    标签: javascript vue.js


    【解决方案1】:

    您可以使用 Vue 实例的 watch 属性为变量更改添加监听器:http://vuejs.org/api/#watch

    watch: {
        'treeData': function (val, oldVal) {
          console.log('new: %s, old: %s', val, oldVal)
        }
    }
    

    如果你要watch@treeData 之类的对象,你可能需要使用deep 标志来观察整个对象树。

    watch: {
        'treeData':  {
            handler:function (val, oldVal){
                console.log('new: %s, old: %s', val, oldVal)
            },
            deep: true
        }
    }
    

    【讨论】:

      【解决方案2】:

      我会在这里改用computed 属性。

      你可以这样做:

      {
        data: {
          treeData: {}
        },
        computed: {
          flatTreeData: function () {
            return flattenTree(this.treeData);
          }
        }
      }
      

      现在这样每次更新treeDataflatTreeData 也会更新。

      【讨论】:

      • 这似乎是更 vue-esque 的解决方案。
      • +1,这是flatTreeData 的最佳选择。 treeData 上的 watch 函数和 flatTreeData 的计算属性会很好。
      • 是的,两者都可以在这种情况下工作,只是认为计算的属性更清晰。
      • 是的,但是他仍然需要监视功能来触发他想要的任何其他事件。计算属性只适用于flatTreeData,所以它不能解决他的问题。
      • 我明白你在说什么,因为我读得更近了。我只是在看代码。
      猜你喜欢
      • 2021-04-05
      • 2019-04-30
      • 2013-11-22
      • 2015-11-18
      • 2019-01-13
      • 1970-01-01
      • 1970-01-01
      • 2017-05-16
      • 1970-01-01
      相关资源
      最近更新 更多