Vue Template Refs
Focus a real control after Vue has mounted it.
How it works
A template ref gives a component access to a DOM node after rendering. This is useful for focus and integration with browser APIs. It is not the default way to update displayed text; reactive state should still drive ordinary content. useTemplateRef names the binding and returns a nullable ref because the element may not exist before mount or after a conditional branch disappears.
Run the code
Use a separate empty learning folder with Node 22.12+ in the 22 series. The reviewed Node version is 22.15.1. Save all files below with their exact relative paths; downloads may keep only the basename, so create src and any tests folders as listed. This project pins Vue 3.5.44 and Vite 7.3.1. Run npm install, then npm run dev and open the local address Vite prints.
Bhylu has no Vue playground. SFCs, npm imports and routing need this local project; do not paste them into the plain HTML or JavaScript editor. Apache, MySQL and changes to Bhylu server settings are not required. The application is a fictional seed-swap learning fixture.
Example
<script setup>
import { useTemplateRef } from "vue";
const input = useTemplateRef("variety");
function focus() {
input.value?.focus();
}
</script>
<template>
<main>
<h1>Riverside seed swap</h1>
<label for="variety">Variety</label
><input id="variety" ref="variety" /><button @click="focus">
Focus variety</button
><output data-result>Focus stays in the form</output>
</main>
</template>
Expected result
The button moves focus to the variety field.
The optional chain handles the period before an element is available. For arrays of repeated refs do not assume the order is a permanent item-identity map. Component refs expose a component interface, so prefer an explicit defineExpose contract when an imperative action is genuinely necessary.
Check APIs and version differences in the official Vue guide.