可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
ready: function() { this.$watch('things', function(){console.log('a thing changed')}, true); }
things
is an array of objects [{foo:1}, {foo:2}]
$watch
detects when an object is added or removed, but not when values on an object are changed. How can I do that?
回答1:
You should pass an object instead of boolean as options
, so:
ready: function () { this.$watch('things', function () { console.log('a thing changed') }, {deep:true}) }
Or you could set the watcher into the vue
instance like this:
new Vue({ ... watch: { things: { handler: function (val, oldVal) { console.log('a thing changed') }, deep: true } }, ... })
[demo]
回答2:
If someone needs to get an item that was changed inside the array, please, check it:
JSFiddle Example
The post example code:
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 } }, ... })