VueJS $watch $refs

2019-02-16 18:03发布

Is it possible to $watch Vue $refs?

I'm wanting to set logic against a child component that is nested inside my current Vue instance but inside the ready callback, $refs.childcomponent is initially undefined while it's processed.

inside ready()

this.$watch('$refs', function() {
    console.log("not firing");
}, { deep: true });

Result: Error: Maximum call stack exceeded

watch property of the instance

watch: {
  '$refs': {
     handler: function() { console.log("hit"); },
     deep: true
  }
}

result: nothing.

3条回答
祖国的老花朵
2楼-- · 2019-02-16 18:35

You can $watch $refs.<name>.<data> but not $refs.<name> itself, not to mention $refs.

https://jsfiddle.net/kenberkeley/9pn1uqam/

查看更多
forever°为你锁心
3楼-- · 2019-02-16 18:37

No, $refs are not reactive, watch won't work.

查看更多
Bombasti
4楼-- · 2019-02-16 18:44

In mounted use code below:

this.$watch(
        () => {
            return this.$refs.<name>.<data>
        },
      (val) => {
        alert('$watch $refs.<name>.<data>: ' + val)
      }
    )
查看更多
登录 后发表回答