Vue’s template rendering abstracts most of the DOM operations. And yet you might run into a situation where you need to access a given DOM element. Vue uses “refs” to access DOM elements with the ref
attribute on that element.
This tutorial shows you how to reference elements in your DOM in Vue’s composition API (using script setup
).
Vue.js 3 Series Overview
Access a DOM Element Using Refs
You can use the ref
attribute on an HTML element to reference it. Assign a value to the ref
attribute to make it accessible in your script setup
block. Inside your script
you can then use Vue’s ref
utility method to create a reference to the related DOM element by assigning the same variable name as used in the DOM element’s ref
assignment:
<script setup>
import { ref } from 'vue'
// the variable name must match the HTML attribute’s `ref` value
const accessor = ref()
</script>
<template>
<div ref="accessor"></div>
</template>
Notice: the DOM element reference is undefined
on the first render and only available after the component is mounted because the component doesn’t exist until the first rendering.
Typing a Template ref
In TypeScript you probably want to narrow the type of the referenced DOM element. You can assign the types as part of the ref<Type | OtherType | undefined>()
setup. Remember to assign the undefined
or null
types, because the DOM element isn’t available until the first render.
For example, if you’re referencing an HTML input element and want to focus it on app start, use optional chaining to ensure the element is defined before calling the focus()
method:
<script setup lang="ts">
import { ref, onMounted } from 'vue'
const element = ref<HTMLInputElement | undefined>()
onMounted(() => {
element.value?.focus()
})
</script>
<template>
<input ref="element" />
</template>
Enjoy!