Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the vue documentation say refs are not reactive when indeed they are

Tags:

vue.js

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?

like image 540
Damilola Olowookere Avatar asked Feb 28 '19 14:02

Damilola Olowookere


Video Answer


1 Answers

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.

like image 68
thanksd Avatar answered Oct 20 '22 16:10

thanksd