Vue Template Refs useTemplateRef DOM Access is an important Vue JS topic because it appears in real projects, debugging sessions, and interviews. Learn the meaning first, then connect it to a small working example so the rule does not stay abstract.
For this page, focus on what problem Vue Template Refs useTemplateRef DOM Access solves, where developers usually make mistakes, and how to verify the result. The audit note for this lesson was: under 650 content words; limited checklist/practice/mistake/FAQ notes .
A strong understanding of Vue Template Refs useTemplateRef DOM Access should include syntax, behavior, one realistic use case, one failure case, and one quick way to check your work with tools or output.
Vue Template Refs useTemplateRef DOM Access should be studied as a practical Vue application development lesson, not as a label. Start by naming the input, the rule that changes the input, and the result a learner should be able to predict after reading the page.
In the vue-js > template-refs page, the notes should connect the definition with a working scenario, a mistake that beginners actually make, and the exact check that proves the fix. That makes the topic useful for coding, debugging, and interview revision.
Template refs give you direct access to a DOM element or child component instance. Use them when you need to do something that Vue's declarative model can't handle - like focusing an input, measuring element dimensions, or calling a method on a child component.
<template>
<div>
<!-- ref attribute - matches the ref name in script -->
<input ref="inputEl" placeholder="I'll be focused on mount" />
<button @click="focusInput">Focus Input</button>
<!-- Canvas ref -->
<canvas ref="canvasEl" width="300" height="150"></canvas>
<!-- Measure element -->
<div ref="boxEl" class="box">Measure me</div>
<p>Box size: {{ boxSize.width }}x{{ boxSize.height }}</p>
<!-- v-for refs - array of elements -->
<ul>
<li v-for="item in items" :key="item.id" :ref="el => setItemRef(el, item.id)">
{{ item.name }}
</li>
</ul>
<button @click="scrollToItem(2)">Scroll to item 2</button>
</div>
</template>
<script setup>
import { ref, reactive, onMounted, useTemplateRef } from 'vue'
// Modern API (Vue 3.5+)
const inputEl = useTemplateRef('inputEl')
const canvasEl = useTemplateRef('canvasEl')
const boxEl = useTemplateRef('boxEl')
// Or classic ref (same name as ref attribute)
// const inputEl = ref(null)
const items = ref([
{ id: 1, name: 'Item One' },
{ id: 2, name: 'Item Two' },
{ id: 3, name: 'Item Three' },
])
const boxSize = reactive({ width: 0, height: 0 })
const itemRefs = new Map()
onMounted(() => {
// Access DOM element after mount
inputEl.value?.focus()
// Draw on canvas
const ctx = canvasEl.value?.getContext('2d')
if (ctx) {
ctx.fillStyle = '#42b883'
ctx.fillRect(10, 10, 280, 130)
ctx.fillStyle = 'white'
ctx.font = '24px Arial'
ctx.fillText('Vue Canvas!', 80, 80)
}
// Measure element
if (boxEl.value) {
const rect = boxEl.value.getBoundingClientRect()
boxSize.width = Math.round(rect.width)
boxSize.height = Math.round(rect.height)
}
})
function focusInput() {
inputEl.value?.focus()
inputEl.value?.select()
}
function setItemRef(el, id) {
if (el) itemRefs.set(id, el)
else itemRefs.delete(id)
}
function scrollToItem(id) {
itemRefs.get(id)?.scrollIntoView({ behavior: 'smooth' })
}
</script>
<!-- ChildComponent.vue -->
<template>
<div>
<input ref="inputEl" v-model="value" />
<p>Internal count: {{ count }}</p>
</div>
</template>
<script setup>
import { ref, useTemplateRef } from 'vue'
const value = ref('')
const count = ref(0)
const inputEl = useTemplateRef('inputEl')
// defineExpose - explicitly expose what parent can access
// Without defineExpose, <script setup> components are closed by default
defineExpose({
// Expose methods
focus() {
inputEl.value?.focus()
},
clear() {
value.value = ''
},
increment() {
count.value++
},
// Expose data (read-only)
getValue: () => value.value,
// Expose ref directly
count,
})
</script>
<!-- Parent.vue - accessing child component methods -->
<template>
<div>
<ChildComponent ref="childRef" />
<button @click="childRef?.focus()">Focus Child Input</button>
<button @click="childRef?.clear()">Clear Child Input</button>
<button @click="childRef?.increment()">Increment Child Count</button>
<p>Child value: {{ childRef?.getValue() }}</p>
<p>Child count: {{ childRef?.count }}</p>
</div>
</template>
<script setup>
import { useTemplateRef, onMounted } from 'vue'
import ChildComponent from './ChildComponent.vue'
const childRef = useTemplateRef('childRef')
onMounted(() => {
// Access exposed methods after mount
childRef.value?.focus()
})
</script>
Understanding Template Refs is not just about syntax. In production applications, this topic directly affects maintainability, debugging speed, and team collaboration. Focus on readability, small reusable patterns, and predictable state flow when implementing Template Refs.
A practical approach is to first implement the simplest working version, then refactor into reusable pieces (components/composables/stores) only when duplication appears. This helps keep your Vue codebase clean while avoiding over-engineering.
When studying Vue Template Refs useTemplateRef DOM Access, separate three things: the concept, the syntax, and the situation where it is useful. This prevents the lesson from becoming a list of commands with no practical meaning.
In Vue JS, Vue Template Refs useTemplateRef DOM Access becomes easier when you build a tiny example first, then increase complexity. Add one realistic input, one invalid or boundary input, and one explanation of why the result changes.
const state = { topic: "Vue Template Refs useTemplateRef DOM Access", ready: true };
if (state.ready) {
console.log(state.topic + ": render or run the normal path");
}
const response = null;
const message = response?.message ?? "Vue Template Refs useTemplateRef DOM Access: show a clear fallback";
console.log(message);
Memorizing Vue Template Refs useTemplateRef DOM Access without the situation where it is useful.
Connect Vue Template Refs useTemplateRef DOM Access to a concrete Vue application development task.
Testing Vue Template Refs useTemplateRef DOM Access only with the perfect input.
Include empty, missing, duplicate, incompatible, or failed cases when relevant.
Changing code before reading the visible symptom or error message.
Inspect the output, state, configuration, or stack trace connected to Vue Template Refs useTemplateRef DOM Access.
Memorizing Vue Template Refs useTemplateRef DOM Access without the situation where it is useful.
Connect Vue Template Refs useTemplateRef DOM Access to a concrete Vue application development task.
The common mistake is memorizing syntax without understanding when the behavior changes or fails.
Remember the problem it solves in Vue application development, then attach the syntax or steps to that problem.
You can predict the result of a small example, explain a failure case, and choose it over a nearby alternative for a clear reason.
They often copy the syntax but skip the state, input, dependency, selector, route, type, or configuration that controls the behavior.
Explore 500+ free tutorials across 20+ languages and frameworks.