Vue3 Fundamentals · Vue 3 + TypeScript

Typed template refs

Typed template refs

A template ref points at a DOM element or a child component, so you can call methods on it. In a <script setup lang="ts"> block useTemplateRef returns a ref whose type you choose with a type parameter.

<script setup lang="ts">
import { useTemplateRef } from 'vue';

const input = useTemplateRef<HTMLInputElement>('input');
</script>

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

The string 'input' matches the ref="input" attribute in the template, so Vue fills the ref when the element mounts. The type parameter says what the element is, so input.value is an HTMLInputElement and the editor offers its methods — focus, select, value.

The ref is null until the element mounts, so input.value is typed HTMLInputElement | null. Guard it with input.value?.focus() or check it first. The type parameter is what makes the ref useful: without it input.value is any, and the editor cannot offer focus or check the call.

In App.vue, focus the input through a typed template ref.

Challenge

The button does nothing because the input is never focused. Export an App component from App.vue that holds the input in a useTemplateRef<HTMLInputElement>('input'), binds it with ref="input", and focuses it when the button is clicked.

The Test mounts your component, clicks the button, and checks which element has focus. The starter never binds the ref, so the input is never focused and the Test fails.

App.vue
<script setup lang="ts">
import { useTemplateRef } from 'vue';

const input = useTemplateRef<HTMLInputElement>('input');

function focusInput() {
  input.value?.focus();
}
</script>

<template>
  <input />
  <button @click="focusInput">Focus</button>
</template>

No test run yet

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