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.
To watch refs with Vue. js, we can watch the reactive properties in the ref if the ref is assigned to a component. to watch the counter 's i reactive property. Since we assigned the counter ref to the counter component, i is a reactive property in counter .
ref is a special attribute, similar to the key attribute discussed in the v-for chapter. It allows us to obtain a direct reference to a specific DOM element or child component instance after it's mounted.
Using watchers in Vue # vue file we can watch for changes in data or props by using watch . For example, the below code will watch for a change in the data element pageData , and run a function according to the value it is changed to.
You can put a watcher on any reactive property. This includes computed props, props, as well as data that is specified inside of data() on your Vue component. They're really useful for creating side effects — things that don't update your application's state immediately.
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) })
No, $refs
are not reactive, watch won't work.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With