Javascript is required
·
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
1<script setup>
2import { ref } from 'vue'
3
4const input = ref(null)
5</script>
6
7<template>
8  <input ref="input" />
9</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
1<script setup>
2import { reactive, watchEffect } from 'vue'
3
4const input = reactive(null)
5
6watchEffect(() => console.log(input));
7</script>
8
9<template>
10  <input ref="input" />
11</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.