javascriptvue.js

VueJS $watch $refs


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.


Solution

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

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

    const Counter = {
      data: () => ({
        i: 0
      }),
      template: `<fieldset>
        <p>Counter</p>
        <code>i = {{ i }}</code>
        <button @click="i += 1"> Add One </button>
      </fieldset>`
    }
    
    const App = {
      components: { Counter },
      mounted () {
        this.$watch(
            () => {
                return this.$refs.counter.i
            },
          (val) => {
            alert('App $watch $refs.counter.i: ' + val)
          }
        )
      },
      template: `<fieldset>
        <p>App</p>
        <counter ref="counter" />
      </fieldset>`
    }
    
    new Vue({
        el: '#app',
        render: h => h(App)
    })