Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

vue.js $watch array of objects

Tags:

vue.js

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?

like image 903
Farzher Avatar asked Dec 15 '15 08:12

Farzher


People also ask

How do I watch an array in Vue?

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.

How do you watch objects in Vue?

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 .

What does watch do in VUE JS?

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.

Can you watch a computed property Vue?

Yes, you can setup watcher on computed property, see the fiddle.


2 Answers

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]

like image 77
Pantelis Peslis Avatar answered Sep 28 '22 02:09

Pantelis Peslis


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     }   },   ... }) 
like image 28
Jonatan Machado Avatar answered Sep 28 '22 03:09

Jonatan Machado