·
1 min read

Vue Tip: Don't Use Reactive Object for Template Refs

Vue Tip: Don't Use Reactive Object for Template Refs Image

Template Refs are a way to access elements in the DOM from within a Vue component. As the name suggests, you should use a ref to access the element in the template.

Let's take a look at a simple example:

Component.vue
<script setup> import { ref } from 'vue' const input = ref(null) </script> <template> <input ref="input" /> </template>

The input variable is a ref that holds the reference to the input element, the name must match the template ref value.

But what if you want to use a reactive object to store the reference? This is not recommended, and here's why:

Component.vue
<script setup> import { reactive, watchEffect } from 'vue' const input = reactive(null) watchEffect(() => console.log(input)); </script> <template> <input ref="input" /> </template>

The watcher will log null when the component is first instantiated, but when the component is mounted and the input is created, it will not trigger again. This happens because the input object becomes a new object which breaks reactivity if we use reactive. Read Ref vs. Reactive: What to Choose Using Vue 3 Composition API? to learn more about reactivity.

If we use ref instead, it will work as expected because only a ref can be reassigned in this way.

StackBlitz

Try it yourself in the following StackBlitz:

If you liked this Vue tip, follow me on X to get notified about new tips, blog posts, and more. Alternatively (or additionally), you can subscribe to my weekly Vue & Nuxt newsletter:

I will never share any of your personal data. You can unsubscribe at any time.