Template refs only exist after the component is mounted. Thus, it’s necessary to type template refs with a union type that includes the DOM element type as well as null:
1<template>
2 <textarea ref="textareaRef" />
3</template>
4
5<script setup lang="ts">
6import { ref, onMounted } from 'vue'
7
8const textareaRef = ref<HTMLTextAreaElement | null>(null)
9
10onMounted(() => {
11 textareaRef.value?.focus()
12})
13</script>
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.