Skip to content

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

Open
@haizhilin2013

Description

@haizhilin2013
Collaborator

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

Activity

wenyejie

wenyejie commented on Jun 17, 2019

@wenyejie

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

April-Zheng

April-Zheng commented on Jul 1, 2019

@April-Zheng

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

lancelote-zpc

lancelote-zpc commented on Mar 18, 2020

@lancelote-zpc

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

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

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

crush2020 commented on Feb 2, 2021

@crush2020

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

yxllovewq

yxllovewq commented on Mar 9, 2022

@yxllovewq

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

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

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

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

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

      Development

      No branches or pull requests

        Participants

        @wenyejie@haizhilin2013@April-Zheng@lancelote-zpc@crush2020

        Issue actions

          [vue] watch怎么深度监听对象变化 · Issue #265 · haizlin/fe-interview