vue.js $ watch对象数组

vue.js Vue.js

猿路易

2020-03-12

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

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

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

第880篇《vue.js $ watch对象数组》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

1个回答
路易卡卡西 2020.03.12

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

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
    }
  },
  ...
})

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android