Vue3 Fundamentals · Composition & Reuse

Template refs

Template refs

Templates and scripts usually stay apart: the template renders, the script holds data. Sometimes the script needs the DOM element itself — to focus an input, to measure a box, to call a method on a child component.

A template ref connects the two. Tag an element with ref, then read it from the script. Vue 3.5 adds useTemplateRef, which returns the ref for you:

<script setup>
import { onMounted, useTemplateRef } from 'vue';

const input = useTemplateRef('input');

onMounted(() => {
  input.value.focus();
});
</script>

<template>
  <input ref="input" />
</template>

The name you pass to useTemplateRef must match the ref attribute in the template. The ref is null until the element exists, so read it in onMounted or later, never during setup.

The Test mounts your component and waits a tick, then checks that the input is the document's active element. The starter never focuses it, so the body stays active and the Test fails. Reach the element through the ref in App.vue.

Challenge

The input never receives focus when the component mounts. Export an App component from App.vue that holds the input with useTemplateRef('input') and focuses it from onMounted.

The Test mounts your component, waits a tick, and checks the input is the document's active element. The starter never focuses it, so the body stays active and the Test fails. Call focus() on the ref.

App.vue
<script setup>
import { onMounted, useTemplateRef } from 'vue';

const input = useTemplateRef('input');

onMounted(() => {
  input.value.blur();
});
</script>

<template>
  <input ref="input" />
</template>

No test run yet

The Test is hidden. Run it to check the Challenge — you only see the result, never the test source.