Vue.js - How to properly watch for nested data Vue.js - How to properly watch for nested data vue.js vue.js

Vue.js - How to properly watch for nested data


You can use a deep watcher for that:

watch: {  item: {     handler(val){       // do stuff     },     deep: true  }}

This will now detect any changes to the objects in the item array and additions to the array itself (when used with Vue.set). Here's a JSFiddle: http://jsfiddle.net/je2rw3rs/

EDIT

If you don't want to watch for every change on the top level object, and just want a less awkward syntax for watching nested objects directly, you can simply watch a computed instead:

var vm = new Vue({  el: '#app',  computed: {    foo() {      return this.item.foo;    }  },  watch: {    foo() {      console.log('Foo Changed!');    }  },  data: {    item: {      foo: 'foo'    }  }})

Here's the JSFiddle: http://jsfiddle.net/oa07r5fw/


Another good approach and one that is a bit more elegant is as follows:

 watch:{     'item.someOtherProp': function (newVal, oldVal){         //to work with changes in someOtherProp     },     'item.prop': function(newVal, oldVal){         //to work with changes in prop     } }

(I learned this approach from @peerbolte in the comment here)


VueJs deep watch in child objects

new Vue({    el: "#myElement",    data: {        entity: {            properties: []        }    },    watch: {        'entity.properties': {            handler: function (after, before) {                // Changes detected. Do work...                 },            deep: true        }    }});


matomo