mounted: 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?
You need to set deep to true when watching an array or object so that Vue knows that it should watch the nested data for changes. Join 11,067 other Vue devs and get exclusive tips and insights delivered straight to your inbox, every week.
Deep watcher over array of objects. vue , we have to import it in the App. vue file and pass users as a prop . In User. vue , we are using watcher over the value which is changing and we are also using user.name property instead of user so that vue can detect the change happening to user.name .
A watcher in Vue is a special feature that allows us to observe some data and perform specific actions when it changes. It is a more generic way to observe and react to data changes in the Vue instance.
Yes, you can setup watcher on computed property, see the fiddle.
You should pass an object instead of boolean as options
, so:
mounted: 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]
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 } }, ... })
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With