Since Vue 3.5, you can use the useTemplateRef()
function to type template refs with TypeScript.
This function automatically infers the correct type for the template ref based on what element or component the matching ref
attribute is used on:
As you can see in the example above, the ref can only be accessed after the component is mounted. Therefore, we use the onMounted
lifecycle hook to focus on the input element. In a template expression, myInput
will be null
on the first render because the element doesn't exist at that point.
If the auto-inference doesn't work as expected, you can provide a type argument to useTemplateRef()
to specify the type explicitly:
Usage before 3.5
Before Vue 3.5, you had to use ref
with a name that matches the template ref attribute's value. You need to cast the ref value to an explicit type via a generic argument:
The initial ref value is null
until the component is mounted or if the v-if
directive unmounts the element. Therefore, we use optional chaining to access textareaRef.value
.
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: Avoid Side Effects in Computed Properties
It is considered bad practice to introduce side effects inside computed properties and functions because it makes the code unpredictable and hard to understand.
Vue Tip: Lifecycle Hooks for Debugging
Vue provides two lifecycle hooks that we can use for debugging purposes.