Vue.js事件,以便在数据更新后激发

Vue.js event to fire after data is updated

本文关键字:更新 数据 js 事件 Vue      更新时间:2023-09-26

我有一个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);
});

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

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

如果要对treeData这样的对象执行watch,则可能需要使用deep标志来监视整个对象树。

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

我会在这里使用computed属性。

你可以做:

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

现在,每次更新treeData时,flatTreeData也会更新。