vue.js $watch 对象数组

新手上路,请多包涵
mounted: function() {
  this.$watch('things', function(){console.log('a thing changed')}, true);
}

things 是一个对象数组 [{foo:1}, {foo:2}]

$watch 检测何时添加或删除对象,但不检测对象上的值何时更改。我怎样才能做到这一点?

原文由 Farzher 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 503
2 个回答

您应该传递一个对象而不是布尔值作为 options ,所以:

 mounted: function () {
  this.$watch('things', function () {
    console.log('a thing changed')
  }, {deep:true})
}

或者您可以将观察程序设置为 vue 实例,如下所示:

 new Vue({
  ...
  watch: {
    things: {
      handler: function (val, oldVal) {
        console.log('a thing changed')
      },
      deep: true
    }
  },
  ...
})

[演示]

原文由 Pantelis Peslis 发布,翻译遵循 CC BY-SA 4.0 许可协议

如果有人需要获取在数组中更改的项目,请检查它:

JSFiddle 示例

帖子示例代码:

 new Vue({
  ...
  watch: {
    things: {
      handler: function (val, oldVal) {
        var vm = this;
        val.filter( function( p, idx ) {
            return Object.keys(p).some( function( prop ) {
                var diff = p[prop] !== vm.clonethings[idx][prop];
                if(diff) {
                    p.changed = true;
                }
            })
        });
      },
      deep: true
    }
  },
  ...
})

原文由 Jonatan Machado 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏