fe-interview icon indicating copy to clipboard operation
fe-interview copied to clipboard

[vue] watch怎么深度监听对象变化

Open haizhilin2013 opened this issue 7 years ago • 5 comments

[vue] watch怎么深度监听对象变化

haizhilin2013 avatar Jun 16 '19 14:06 haizhilin2013

'a.b.c', 然后直接解析到c那层, 绑定observer

wenyejie avatar Jun 17 '19 01:06 wenyejie

'obj.xx': { handler: function(val) {}, deep:true }

April-Zheng avatar Jul 01 '19 02:07 April-Zheng

deep设置为true 就可以监听到对象的变化

    let vm=new Vue({
        el:"#first",
        data:{msg:{name:'北京'}},
        watch:{

            msg:{
                handler (newMsg,oldMsg){
                    console.log(newMsg);
                },
                immediate:true,
                deep:true
            }
        }
    })

lancelote-zpc avatar Mar 18 '20 06:03 lancelote-zpc

选项:deep 为了发现对象内部值的变化,可以在选项参数中指定 deep: true。注意监听数组的变更不需要这么做。

crush2020 avatar Feb 02 '21 01:02 crush2020

为什么无法监听对象的属性,因为对象保存的是地址。 如何监听对象obj的属性a:

watch: {
  'obj.a': {
    deep: true,
    handler(newValue, oldValue){},
  }
}

如何监听对象obj的所有属性:

watch: {
 obj: {
    deep: true,
    handler(newObj, oldOb j){},
  }
}

注意:如果直接监听到具体的某个属性值则获取到的是newValue和oldValue,如果监听属性所属的对象或者祖先对象,则返回的是对应变更后的对象。

yxllovewq avatar Mar 09 '22 08:03 yxllovewq