Vue · Junior · Question 43 of 75

How do you get a reference to a DOM element in <script setup> (Vue 3.5+)?

<script setup>
import { useTemplateRef, onMounted } from "vue";
const input = useTemplateRef("search");
onMounted(() => input.value.focus());
</script>
<template><input ref="search" /></template>

Explanation

Before 3.5 you declared const search = ref(null) with the same name as the ref attribute. The value is null until the element is mounted.

Further reading

Problem with a question

Vue · Junior · question 43

Test yourself

Take the Vue · Junior quiz: questions and options are shuffled, and you get a review of your mistakes at the end.

Take this quiz