[Vue] Vue 3.5 useTemplateRef
A template ref is a ref that connects to an element and allows you to manipulate the underlying HTML element using the DOM API.
This is generally not recommended in reactive programming, but there are some situations where you might need to rely on using a template ref. For instance, if you want a textbox to be focused-on when the component is mounted.
<script setup lang="ts">
import { ref } from 'vue'
const inputRef = ref<HTMLInputElement | null>(null)
onMounted(() => {
inputRef.value!.focus()
})
</script>
<template>
<input ref="inputRef" />
</template>
You just access the value of the ref to get the HTML element, and call focus on that.
Now in Vue 3.5, we get a dedicated composable just for that.
<script setup lang="ts">
import { useTemplateRef } from 'vue'
const inputRef = useTemplateRef('input-ref')
onMounted(() => {
inputRef.value!.focus()
})
</script>
Unlike the traditional approach of initializing with null, we now provide a key that maps the ref to the element. This same key must be used in the element’s ref attribute.
<template>
<input ref="input-ref" />
</template>
With this new composable, we get type support without needing to manually specify the type of the element.
If you want to learn more about template ref, you can check out the documentation for that.
Code
<script setup lang="ts">
import { useTemplateRef } from 'vue'
const inputRef = useTemplateRef('input-ref')
onMounted(() => {
inputRef.value!.focus()
})
</script>
<template>
<input ref="input-ref" />
</template>