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:
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:
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:
Vue Tip: Trigger Transition Programmatically
You can programmatically trigger a transition via the "key" attribute.
Nuxt Tip: How Nuxt Uses Nitro, h3 and ofetch Internally
Nitro, h3 and ofetch are UnJS packages that are used to power the Nuxt 3 server engine.