Vue.js course Β· Module 2: Template Syntax
Template Refs
In this lesson5
Sometimes you need direct access to a DOM element - like an engineer who needs to check a physical sensor.
Templates describe how the panel should look, and Vue takes care of the page elements itself. Some tasks, however, cannot be written declaratively: placing the cursor in the command field right after the panel opens, measuring a container, or handing a <canvas> element to an external charting library. Then you need a handle to the real element - and that is what template refs give you. In the second part of the lesson you will also meet a few special directives for unusual jobs.
Basic Template Refs
The special ref attribute marks an element in the template. In the script you declare a ref with the same name and the value null, and once the component is mounted, Vue puts the element into it. The moment of mounting is caught by the onMounted function - a lifecycle hook that Vue calls when the component is already on the page; we will cover the lifecycle in module 6.
<template>
<div class="input-panel" style="background: #0a0e27; padding: 1rem;">
<input ref="inputRef" type="text" placeholder="Module code"
style="background: #0a0e27; border: 1px solid #00b4d8; color: #00ff88; padding: 0.5rem;">
<button @click="focusInput" class="btn-focus">Set focus</button>
</div>
</template>
<script setup>
import { ref, onMounted } from 'vue'
// Name must match the ref attribute in template
const inputRef = ref(null)
function focusInput() {
inputRef.value?.focus()
}
onMounted(() => {
// Element is available after mounting
inputRef.value?.focus()
})
</script>The order is always the same: declare ref(null), put the ref="inputRef" attribute on the element, mount, and only then use it. Before mounting, and also after the element is removed by v-if, the ref holds null, which is why ?. protects you from an error. It is the same ref() function you use for data - here the container simply holds an element instead of a number.
Since Vue 3.5 the recommended way is the useTemplateRef helper. Its argument must match the value of the ref attribute, and the variable can have any name:
<script setup>
import { useTemplateRef, onMounted } from 'vue'
const commandInput = useTemplateRef('command-input')
onMounted(() => {
commandInput.value?.focus()
})
</script>
<template>
<input ref="command-input" placeholder="Module code">
</template>It works identically, and in TypeScript the element type is inferred automatically. The older form still works, and you will meet it in existing code and in the exercises, but in new projects I recommend useTemplateRef.
Refs in v-for
When ref sits on an element with v-for, after mounting you get an array of elements rather than a single element:
<template>
<div class="modules-list">
<ul style="list-style: none; background: #0a0e27;">
<li v-for="module in modules" :key="module.id" ref="itemRefs"
style="color: #00b4d8; padding: 0.5rem; border-left: 2px solid #00ff88;">
{{ module.name }}
</li>
</ul>
</div>
</template>
<script setup>
import { ref, onMounted } from 'vue'
const modules = ref([
{ id: 1, name: 'Oxygen Generator' },
{ id: 2, name: 'Water Recycler' }
])
const itemRefs = ref([])
onMounted(() => {
console.log(itemRefs.value) // Array of LI elements
})
</script>The console shows two li elements. The docs warn, however, that the order of this array does not have to match the order of the data, so do not assume that the element at index 0 is the first module.
Function Refs
Instead of a name you can pass a function by using the dynamic :ref binding. Vue calls it with the element on every component update, and with null when the element is unmounted:
<template>
<input :ref="setInputRef" type="text"
style="background: #0a0e27; border: 1px solid #00ff88; color: #00b4d8;">
</template>
<script setup>
import { ref } from 'vue'
const dynamicRef = ref(null)
function setInputRef(el) {
dynamicRef.value = el
console.log('Element set:', el)
}
</script>You decide where to store the element, for example in a map keyed by an identifier. Just remember the null case.
Refs on Components
A ref attribute on a component gives you access to its instance. SensorPanel.vue is a separate component file, imported like any other module - we will deal with components in module 6. The parent calls the child's method after mounting:
<template>
<SensorPanel ref="sensorRef" />
</template>
<script setup>
import { ref, onMounted } from 'vue'
import SensorPanel from './SensorPanel.vue'
const sensorRef = ref(null)
onMounted(() => {
// Access component methods and properties
sensorRef.value?.refreshData()
})
</script>Components using <script setup> are private by default: the parent sees nothing until the child exposes it with the defineExpose macro, which does not need to be imported:
<!-- SensorPanel.vue - must expose methods -->
<script setup>
import { ref } from 'vue'
const sensorData = ref({})
function refreshData() {
console.log('Refreshing sensor data!')
}
// defineExpose - make available to the parent
defineExpose({
refreshData,
sensorData
})
</script>defineExpose has to be called before the first await. This kind of connection couples components tightly, so use it sparingly - props and events are usually the better choice.
Special Directives
A few built-in directives solve rarer tasks, but they are worth knowing. v-text sets the element's textContent, so it replaces the element's entire content, while mustaches replace only their own fragment:
<template>
<p v-text="statusMessage"></p>
<p>Status: {{ statusMessage }}</p>
</template>Both paragraphs show the message, but only the second one keeps the Status label. v-once renders an element once and then treats it as static. v-memo (Vue 3.2+) memoizes a fragment of the template and updates it only when one of the values in its array changes:
<template>
<p v-once>Mission code: {{ missionCode }}</p>
<div v-for="module in modules" :key="module.id" v-memo="[module.id === selectedId]">
{{ module.name }} - selected: {{ module.id === selectedId }}
</div>
</template>A later change of missionCode will not refresh the paragraph. After selectedId changes, only the two modules whose flag changed are re-rendered. v-memo="[]" works like v-once, and badly chosen dependencies leave stale data on screen, which is why it is a tool for very long lists. The last two directives concern compilation:
<template>
<code v-pre>{{ this will not be compiled }}</code>
</template>
<style>
[v-cloak] {
display: none;
}
</style>v-pre skips compilation of the element and its children, so you see the mustaches literally. v-cloak is needed only without a build step, when Vue compiles a template written directly in HTML: together with this CSS rule it hides the raw {{ }} until the app is mounted. In a Vite project you do not need it.
Treat template refs as a last resort - first check whether the template is enough. In the module project you will combine all these tools into one hologram panel.
Remember: a template ref is a service key to a single device - you reach for it only after mounting, and only when the control panel is not enough.
Code for this lesson: App.vue
<script setup>
import { ref, onMounted } from 'vue'
// Template refs
const inputRef = ref(null)
const containerRef = ref(null)
const canvasRef = ref(null)
// Data
const focusCount = ref(0)
const containerInfo = ref({})
const canvasDrawn = ref(false)
// Reactive data for v-once demonstration
const staticData = ref({
launchDate: '2087-03-15',
missionCode: 'NOVA-MARS-001',
initialCrew: 6
})
const dynamicCounter = ref(0)
// Functions
function focusInput() {
if (inputRef.value) {
inputRef.value.focus()
focusCount.value++
}
}
function getContainerDimensions() {
if (containerRef.value) {
const rect = containerRef.value.getBoundingClientRect()
containerInfo.value = {
width: Math.round(rect.width),
height: Math.round(rect.height),
top: Math.round(rect.top),
left: Math.round(rect.left)
}
}
}
function drawOnCanvas() {
if (canvasRef.value) {
const ctx = canvasRef.value.getContext('2d')
const canvas = canvasRef.value
// Clear canvas
ctx.fillStyle = '#0a0e27'
ctx.fillRect(0, 0, canvas.width, canvas.height)
// Draw Mars
ctx.beginPath()
ctx.arc(200, 150, 80, 0, Math.PI * 2)
ctx.fillStyle = '#ff6600'
ctx.fill()
// Draw craters
ctx.beginPath()
ctx.arc(180, 130, 20, 0, Math.PI * 2)
ctx.fillStyle = '#cc5500'
ctx.fill()
ctx.beginPath()
ctx.arc(220, 160, 15, 0, Math.PI * 2)
ctx.fill()
// Draw NOVA LAB base
ctx.fillStyle = '#00ff88'
ctx.fillRect(150, 220, 100, 40)
// Draw dome
ctx.beginPath()
ctx.arc(200, 220, 50, Math.PI, 0)
ctx.strokeStyle = '#00b4d8'
ctx.lineWidth = 3
ctx.stroke()
// Add text
ctx.fillStyle = '#00ff88'
ctx.font = 'bold 16px Courier'
ctx.fillText('NOVA LAB', 160, 245)
canvasDrawn.value = true
}
}
function incrementCounter() {
dynamicCounter.value++
}
onMounted(() => {
getContainerDimensions()
// Auto-focus on mount
setTimeout(() => {
focusInput()
}, 500)
})
</script>
<template>
<div class="advanced-lab">
<h1>Advanced Directives - NOVA LAB</h1>
<!-- Template Refs Section -->
<section class="lab-section">
<h2>Template Refs - Accessing DOM Elements</h2>
<!-- Input ref example -->
<div class="demo-card">
<h3>ref on an input - Programmatic focus</h3>
<div class="ref-demo">
<input
ref="inputRef"
type="text"
placeholder="This input can be focused programmatically..."
class="input-field"
>
<button @click="focusInput" class="btn btn-primary">
Focus Input
</button>
</div>
<p class="info-text">Number of focus calls: {{ focusCount }}</p>
<code class="code-hint">ref="inputRef" β inputRef.value.focus()</code>
</div>
<!-- Container ref example -->
<div class="demo-card">
<h3>ref on container - Reading dimensions</h3>
<div ref="containerRef" class="ref-container">
<p>This container has ref="containerRef"</p>
<p>Click button to read its dimensions</p>
</div>
<button @click="getContainerDimensions" class="btn btn-success">
Get Dimensions
</button>
<div v-if="containerInfo.width" class="dimensions-info">
<p>Width: {{ containerInfo.width }}px</p>
<p>Height: {{ containerInfo.height }}px</p>
<p>Position: ({{ containerInfo.left }}px, {{ containerInfo.top }}px)</p>
</div>
</div>
<!-- Canvas ref example -->
<div class="demo-card">
<h3>ref on a canvas - Drawing</h3>
<canvas
ref="canvasRef"
width="400"
height="300"
class="canvas-field"
></canvas>
<button @click="drawOnCanvas" class="btn btn-warning">
{{ canvasDrawn ? 'Redraw' : 'Draw' }} Mars Base
</button>
<code class="code-hint">ref="canvasRef" β canvasRef.value.getContext('2d')</code>
</div>
</section>
<!-- v-once Section -->
<section class="lab-section">
<h2>v-once - One-time rendering</h2>
<div class="demo-card">
<h3>Static data (v-once)</h3>
<div v-once class="static-content">
<p><strong>Launch Date:</strong> {{ staticData.launchDate }}</p>
<p><strong>Mission Code:</strong> {{ staticData.missionCode }}</p>
<p><strong>Initial Crew:</strong> {{ staticData.initialCrew }}</p>
<p class="info-text">This data is rendered only once and will not update</p>
</div>
</div>
<div class="demo-card">
<h3>Comparison: v-once vs normal binding</h3>
<div class="comparison-grid">
<div class="comparison-item">
<h4>With v-once (does not update)</h4>
<div v-once class="counter-display static">
{{ dynamicCounter }}
</div>
</div>
<div class="comparison-item">
<h4>Without v-once (updates)</h4>
<div class="counter-display dynamic">
{{ dynamicCounter }}
</div>
</div>
</div>
<button @click="incrementCounter" class="btn btn-primary">
Increment Counter ({{ dynamicCounter }})
</button>
<p class="info-text">
Left counter stays at the initial value, right one updates
</p>
</div>
</section>
<!-- v-cloak Section -->
<section class="lab-section">
<h2>v-cloak - Hiding unrendered templates</h2>
<div class="demo-card">
<h3>v-cloak - Prevents showing <code v-pre>{{ }}</code></h3>
<div v-cloak class="cloak-demo">
<p>This section uses v-cloak</p>
<p>With slow loading, the user won't see raw mustaches <code v-pre>{{ }}</code></p>
<p>Data: {{ staticData.missionCode }}</p>
</div>
<code class="code-hint">
v-cloak + CSS: [v-cloak] { display: none; }
</code>
</div>
</section>
<!-- Info Box -->
<div class="info-box">
<h3>Advanced Vue directives</h3>
<div class="info-grid">
<div>
<h4>Template Refs:</h4>
<ul>
<li><strong>ref="name"</strong> - Creates a reference to an element</li>
<li><strong>const name = ref(null)</strong> - Declaration in setup</li>
<li><strong>name.value</strong> - Access to DOM element</li>
<li>Available after onMounted()</li>
</ul>
</div>
<div>
<h4>v-once:</h4>
<ul>
<li>Renders the element/component only once</li>
<li>Skips all subsequent updates</li>
<li>Optimization for static content</li>
<li>Useful for large data that does not change</li>
</ul>
</div>
<div>
<h4>v-cloak:</h4>
<ul>
<li>Hides unrendered templates</li>
<li>Requires CSS: [v-cloak] { display: none; }</li>
<li>Prevents "flashing" <code v-pre>{{ }}</code></li>
<li>Removed automatically after compilation</li>
</ul>
</div>
<div>
<h4>Uses of ref:</h4>
<ul>
<li>Programmatic focus on an input</li>
<li>Integration with DOM libraries</li>
<li>Canvas and SVG manipulation</li>
<li>Scrolling to an element</li>
<li>Reading element dimensions</li>
</ul>
</div>
</div>
</div>
</div>
</template>
<style scoped>
/* v-cloak CSS */
[v-cloak] {
display: none;
}
.advanced-lab {
background: linear-gradient(135deg, #0a0e27 0%, #1a1e3f 100%);
min-height: 100vh;
padding: 2rem;
color: #ffffff;
font-family: 'Courier New', monospace;
}
h1 {
text-align: center;
color: #00ff88;
text-shadow: 0 0 20px rgba(0, 255, 136, 0.5);
margin-bottom: 3rem;
}
h2 {
color: #00b4d8;
margin-bottom: 1.5rem;
border-bottom: 2px solid #00b4d8;
padding-bottom: 0.5rem;
}
h3 {
color: #00ff88;
font-size: 1.1rem;
margin-bottom: 1rem;
}
h4 {
color: #00b4d8;
font-size: 1rem;
margin-bottom: 0.75rem;
}
.lab-section {
background: rgba(0, 255, 136, 0.05);
border: 2px solid #00ff88;
border-radius: 10px;
padding: 2rem;
margin-bottom: 2rem;
}
.demo-card {
background: rgba(0, 180, 216, 0.1);
border: 2px solid #00b4d8;
border-radius: 8px;
padding: 1.5rem;
margin-bottom: 1.5rem;
}
.ref-demo {
display: flex;
gap: 1rem;
margin-bottom: 1rem;
flex-wrap: wrap;
}
.input-field {
background: rgba(0, 0, 0, 0.3);
border: 2px solid #00b4d8;
border-radius: 5px;
padding: 0.75rem;
color: #ffffff;
font-family: 'Courier New', monospace;
font-size: 1rem;
flex: 1;
min-width: 250px;
}
.input-field:focus {
outline: none;
border-color: #00ff88;
box-shadow: 0 0 15px rgba(0, 255, 136, 0.5);
animation: focusPulse 0.5s ease;
}
@keyframes focusPulse {
0%, 100% { transform: scale(1); }
50% { transform: scale(1.02); }
}
.ref-container {
background: rgba(0, 255, 136, 0.1);
border: 2px dashed #00ff88;
border-radius: 8px;
padding: 2rem;
text-align: center;
margin: 1rem 0;
}
.dimensions-info {
background: rgba(0, 0, 0, 0.3);
border-left: 4px solid #00ff88;
border-radius: 5px;
padding: 1rem;
margin-top: 1rem;
}
.dimensions-info p {
margin: 0.5rem 0;
color: #00ff88;
}
.canvas-field {
display: block;
width: 100%;
max-width: 400px;
background: #0a0e27;
border: 2px solid #00b4d8;
border-radius: 8px;
margin: 1rem 0;
}
.static-content {
background: rgba(0, 255, 136, 0.1);
border: 2px solid #00ff88;
border-radius: 8px;
padding: 1.5rem;
}
.static-content p {
margin: 0.75rem 0;
color: #ffffff;
}
.static-content strong {
color: #00b4d8;
}
.comparison-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
gap: 1.5rem;
margin: 1.5rem 0;
}
.comparison-item {
background: rgba(0, 0, 0, 0.3);
border-radius: 8px;
padding: 1.5rem;
text-align: center;
}
.counter-display {
font-size: 3rem;
font-weight: bold;
padding: 2rem;
border-radius: 8px;
margin: 1rem 0;
}
.counter-display.static {
background: rgba(255, 180, 0, 0.2);
border: 2px solid #ffb400;
color: #ffb400;
}
.counter-display.dynamic {
background: rgba(0, 255, 136, 0.2);
border: 2px solid #00ff88;
color: #00ff88;
animation: pulse 2s infinite;
}
.cloak-demo {
background: rgba(0, 180, 216, 0.1);
border: 2px solid #00b4d8;
border-radius: 8px;
padding: 1.5rem;
}
.btn {
padding: 0.75rem 1.5rem;
border: none;
border-radius: 5px;
font-size: 1rem;
font-weight: bold;
cursor: pointer;
transition: all 0.3s ease;
font-family: 'Courier New', monospace;
margin: 0.5rem;
}
.btn-primary {
background: #00ff88;
color: #0a0e27;
}
.btn-success {
background: #00b4d8;
color: #ffffff;
}
.btn-warning {
background: #ffb400;
color: #0a0e27;
}
.btn:hover {
transform: scale(1.05);
box-shadow: 0 5px 15px rgba(0, 255, 136, 0.4);
}
.code-hint {
display: block;
background: rgba(0, 0, 0, 0.5);
border-left: 4px solid #00ff88;
padding: 0.75rem;
border-radius: 5px;
color: #00ff88;
font-family: 'Courier New', monospace;
font-size: 0.9rem;
margin-top: 1rem;
}
.info-text {
color: #00b4d8;
font-size: 0.9rem;
margin-top: 1rem;
}
.info-box {
background: rgba(0, 255, 136, 0.05);
border: 2px solid #00ff88;
border-radius: 10px;
padding: 2rem;
}
.info-box h3 {
margin-top: 0;
margin-bottom: 1.5rem;
}
.info-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
gap: 2rem;
}
.info-box ul {
list-style: none;
padding: 0;
}
.info-box li {
padding: 0.5rem 0;
color: #ffffff;
border-left: 3px solid #00b4d8;
padding-left: 1rem;
margin: 0.5rem 0;
}
.info-box strong {
color: #00ff88;
}
@keyframes pulse {
0%, 100% { opacity: 1; }
50% { opacity: 0.7; }
}
</style>Docs entries used in this lesson
Spotted a mistake in this lesson?
Check yourself
Answer the questions from this lesson. Pick an answer to see right away whether it is correct.
1. Which Vue mechanism gives direct access to a DOM element from the component's template?
2. What is the difference between {{ }} and v-text?
3. What does v-pre do?
4. What does the v-once directive do in Vue.js?
5. missionCode changes from 'A-1' to 'B-2'. What does <p v-once>Code: {{ missionCode }}</p> show then?
6. Why would you use v-cloak?
7. Why should you be careful when using v-html?
8. Which Vue directive is used for performance optimization through memoization?
9. Which key modifier in Vue.js is used to detect the Escape key?
10. What should you do when a template becomes too complex?
11. What does v-memo do in Vue 3?
12. Which binding calls onSelf only when the element itself is clicked, not its child?
13. Which practice is recommended in Vue templates?
Hands-on tasks in the game
- Code editor
Use a template ref to automatically focus an input after the component mounts.
- Vertical ordering
Order the steps of using a template ref:
- Vertical ordering
Arrange the template ref code pieces in the order they take effect:
- Click in order
Arrange the template ref code with auto-focus:
- Vertical ordering
Arrange the style binding methods from simple to advanced:
- Vertical ordering
Order the steps of v-if in Vue:
- Horizontal ordering
Arrange the correct v-for syntax with index access:
Tasks after this lesson
- QuestionAccessing DOM via Template Ref
- QuestionThe v-text Directive
- Coding taskPractice: Template Refs
- Put in orderTemplate Ref Lifecycle
- Put in orderTemplate Ref Syntax
- QuestionThe v-pre Directive
- QuestionThe v-once Directive
- Click in orderTemplate Ref Syntax with onMounted
- Questionv-once After a Data Change
- QuestionThe v-cloak Directive
- Put in orderInline Style Binding Methods
- Questionv-html Security
- QuestionDirective for Memoization
- QuestionEscape Key Modifier
- Put in orderConditional Rendering Process
- QuestionTemplate Complexity
- Questionv-memo in Vue 3
- Put in orderv-for Syntax with Index
- QuestionThe .self Modifier
- QuestionTemplate Best Practices