Vue Template Refs
Vue updates the DOM for you, so most of the time you never touch elements directly. A few tasks still need the real element: focusing an input, scrolling to a position, measuring a size, playing a video, or handing an element to a non-Vue library (a chart, a map, a rich-text editor). For that, Vue provides template refs.
Add a ref attribute with a name to an element; after the component is mounted you can access that element in code.
Options API: this.$refs
<div id="app">
<input ref="nameInput" placeholder="Your name">
<button @click="focusInput">Focus the input</button>
<button @click="measure">Measure the box</button>
<div ref="box" style="width: 70%; padding: 10px; background: #ecfdf5; margin-top: 8px">I am a box.</div>
</div>
<script type="module">
import { createApp } from 'vue';
createApp({
mounted() {
this.$refs.nameInput.focus(); // auto-focus when the app appears
},
methods: {
focusInput() {
this.$refs.nameInput.focus();
},
measure() {
const r = this.$refs.box.getBoundingClientRect();
console.log(`box is ${Math.round(r.width)} × ${Math.round(r.height)} px`);
}
}
}).mount('#app');
</script>$refs is filled after rendering. In created (or in the very first render) it is still empty — use refs from mounted onward, or in event handlers.
Composition API: a ref with the same name
With setup(), create a ref(null) and return it under the same name as the ref attribute. Vue fills it with the element once mounted.
<style> video, canvas { display: block; margin: 6px 0; border: 1px solid #ccc; } </style>
<div id="app">
<canvas ref="canvas" width="240" height="100"></canvas>
<button @click="draw">Draw again</button>
</div>
<script type="module">
import { createApp, ref, onMounted } from 'vue';
createApp({
setup() {
const canvas = ref(null); // same name as ref="canvas"
let shift = 0;
function draw() {
const ctx = canvas.value.getContext('2d');
ctx.clearRect(0, 0, 240, 100);
ctx.fillStyle = '#42b883';
for (let i = 0; i < 5; i++) {
ctx.fillRect(10 + i * 45, 90 - ((i + shift) % 5 + 1) * 15, 30, ((i + shift) % 5 + 1) * 15);
}
shift++;
}
onMounted(draw); // the element exists from here on
return { canvas, draw };
}
}).mount('#app');
</script>Note: Vue 3.5 adds
useTemplateRef('canvas'), which looks up the ref by its string name — handy in<script setup>when the variable name differs from the ref name:const el = useTemplateRef('canvas').
Refs inside v-for
When ref is used inside v-for, the ref becomes an array of elements:
<style> li { padding: 4px; } .hl { background: #fef08a; } </style>
<div id="app">
<button v-for="(c, i) in chapters" :key="c" @click="scrollTo(i)">{{ i + 1 }}</button>
<ul style="height: 90px; overflow: auto; border: 1px solid #ddd">
<li v-for="(c, i) in chapters" :key="c" ref="items" :class="{ hl: i === active }">{{ c }}</li>
</ul>
</div>
<script type="module">
import { createApp, ref } from 'vue';
createApp({
setup() {
const chapters = ['Intro', 'Directives', 'Events', 'Forms', 'Components', 'Slots', 'Routing'];
const items = ref([]);
const active = ref(-1);
function scrollTo(i) {
active.value = i;
items.value[i].scrollIntoView({ block: 'nearest', behavior: 'smooth' });
}
return { chapters, items, active, scrollTo };
}
}).mount('#app');
</script>The array order is not guaranteed to match the source array in all cases (for example after reordering), so for complex lists store an id in a data- attribute or use a function ref.
Function refs
:ref can also be a function. Vue calls it with the element on mount, and with null on unmount:
<input :ref="(el) => { inputs[field.id] = el }">Refs on components
A ref on a component gives you the component instance. With the Options API you can call its methods; with setup() or <script setup> the component must explicitly expose what the parent may use:
<div id="app">
<count-down ref="timer" :from="5"></count-down>
<button @click="$refs.timer.restart()">Restart from the parent</button>
</div>
<script type="module">
import { createApp, ref, onUnmounted } from 'vue';
const app = createApp({});
app.component('count-down', {
props: ['from'],
setup(props, { expose }) {
const left = ref(props.from);
const tick = setInterval(() => { if (left.value > 0) left.value--; }, 1000);
onUnmounted(() => clearInterval(tick));
function restart() { left.value = props.from; console.log('restarted'); }
expose({ restart }); // the parent can call only restart()
return { left };
},
template: `<p style="font-size:24px">⏳ {{ left }}</p>`
});
app.mount('#app');
</script>Tip: Reach for template refs only when you really need the DOM or a child's method. Passing data down with props and up with events keeps components independent; calling child methods through refs couples them tightly.
Test yourself
In the Options API, where do you find an element marked with ref="email"?
this.emailthis.$refs.emailthis.$el.emaildocument.refs.email
Why is this.$refs.input undefined inside created()?
- Refs only work in methods
- The DOM has not been rendered yet
- Refs must be declared in
data - It's a bug in Vue
What does a ref inside v-for give you?
- Only the last element
- An array of elements
- A Map keyed by index
- Nothing; refs are not allowed in loops