A quote from the vue official documentation states that
$refs...are not reactive.
However, I have used such refs in templates and they are indeed reactive, and even in methods, computed props, and watchers (as long as you access it after being mounted). Several third party vue libraries e.g. this one also provides features that use/depend on the reactivity of refs.
Can someone please clarify what the official doc meant by refs not being reactive please?
You are misunderstanding what it means for something to be reactive in the context of the Vue framework. Sure, you are able to access the value of the $refs
object after they have been set when the component is mounted, but that does not mean that the object is reactive.
When data is reactive, it means that changes to the value of that data will trigger a "reaction" from some part of the component that depends on that data's value, such as re-rendering the template, recalculating a computed variable, or triggering a watcher.
Read through the documentation on reactivity.
Here's an example:
Vue.config.productionTip = false;
Vue.config.devtools = false;
new Vue({
el: '#app',
mounted() {
console.log('$refs.foo in mounted', this.$refs.foo);
},
watch: {
'$refs.foo':{
immediate: true,
handler(value) {
console.log('$refs.foo watcher', value);
}
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<div ref="foo"></div>
<div v-if="$refs.foo">
If $refs.foo was reactive, the template would update and you would see this message
</div>
</div>
In that example, you can see that the watcher for $refs.foo
initially logs that the value of $refs.foo
is undefined
. This makes sense because the watcher has fired before the component has mounted, so the properties of the $refs
object haven't been set yet. Then, in the mounted
hook, we see that the value of $refs.foo
has been set as expected.
If $refs
was reactive, we would then see the template update, because the v-if="$refs.foo"
directive would have evaluated to true
. We would also see the watcher fire again after the value of $refs.foo
was set, logging that new value of $refs.foo
. However, since $refs
is not reactive, neither of those things happen.
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