vue.js $watch array of objects

匿名 (未验证) 提交于 2019-12-03 08:33:39

问题:

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


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!