Template refs and defineExpose
Reaching DOM elements and child components with useTemplateRef, refs in v-for, function refs, and exposing a small public API with defineExpose.
Template refs and defineExpose
The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.
Not started
What you'll learn
- A template ref is an escape hatch to the real DOM element or child component instance, for jobs declarative templates can't do: focusing an input, measuring size, handing an element to a third-party library.
- Since Vue 3.5, `useTemplateRef('name')` returns a ref that matches the element with `ref="name"`. Before 3.5, you declared `const name = ref(null)` with the same name as the attribute.
- A template ref is `null` until the component mounts and goes back to `null` when the element is removed, so read it in `onMounted` or guard for `null` in a watcher.
- A ref inside `v-for` holds an array of elements, in no guaranteed order. A function ref, `:ref="(el) => ..."`, gives you full control and receives `null` on unmount.
- `<script setup>` components are closed by default: a parent's ref to one sees nothing. `defineExpose({ ... })` chooses exactly what to make public, and exposed refs are unwrapped on the instance.
- Exposing methods is for exceptional cases like `focus()` or `reset()`. Props down and events up remains the default way for components to communicate.
When declarative isn’t enough
Almost everything in Vue is declarative. You describe the DOM in a template, change state, and Vue updates the page. A few jobs don’t fit that model:
- moving keyboard focus to an input when a dialog opens
- reading an element’s size or scroll position
- calling a method on a
<video>or<canvas>element - handing a container element to a charting or map library that manages its own DOM
There’s no state you can set that means “focus this now”. You need the actual element, the same object document.querySelector would give you, as covered in DOM manipulation. Querying the document from a component is fragile: it can match another instance of the same component, or something outside the component entirely. Template refs give a component a direct, scoped reference to its own elements.
useTemplateRef (Vue 3.5+)
Mark the element with a ref attribute and look it up with useTemplateRef:
<script setup>
import { useTemplateRef, onMounted } from 'vue'
const searchInput = useTemplateRef('search')
onMounted(() => {
searchInput.value.focus()
})
</script>
<template>
<input ref="search" type="search" />
</template>
useTemplateRef('search') returns a read-only ref whose .value is the <input> element once it exists. The string has to match the ref attribute. The variable name is up to you.
Before Vue 3.5 the convention was different, and most existing code still uses it. You declare a normal ref whose variable name matches the attribute:
<script setup>
import { ref, onMounted } from 'vue'
const search = ref(null) // must be named exactly like ref="search"
onMounted(() => search.value.focus())
</script>
<template>
<input ref="search" />
</template>
Both work in current Vue. useTemplateRef is preferred in new code because the link is an explicit string instead of a naming coincidence. It also works inside composables, where the variable lives in a different file from the template.
One trap follows from the matching rule. Vue resolves a string ref attribute against the component’s top-level bindings, so ref="email" on an element in a component that also has const email = ref('') for form state writes the element into your state ref. Give template refs names that can’t collide, like email-field.
Null until mounted
A template ref is filled in after the component renders. During setup, and in a template expression on the first render, it is null. That is why the examples above read it in onMounted, as covered in lifecycle hooks.
It also goes back to null when the element is removed, for example by a v-if. If you watch a template ref, handle both cases:
watchEffect(() => {
if (searchInput.value) {
searchInput.value.focus()
} else {
// not mounted yet, or removed by v-if
}
})
Refs inside v-for, and function refs
A ref attribute on an element rendered by v-for collects every element into an array:
<script setup>
import { ref, useTemplateRef, onMounted } from 'vue'
const list = ref(['a', 'b', 'c'])
const itemEls = useTemplateRef('items')
onMounted(() => console.log(itemEls.value.length)) // 3
</script>
<template>
<ul>
<li v-for="item in list" :key="item" ref="items">{{ item }}</li>
</ul>
</template>
The Vue docs warn that this array is not guaranteed to be in the same order as the source list. When you need to know which element belongs to which item, use a function ref. Bind :ref to a function, and Vue calls it with the element on mount or update, and with null on unmount:
<script setup>
defineProps(['items'])
const elById = new Map()
</script>
<template>
<li
v-for="item in items"
:key="item.id"
:ref="(el) => (el ? elById.set(item.id, el) : elById.delete(item.id))"
>
{{ item.label }}
</li>
</template>
Refs to child components
A ref on a component gives you that component’s instance instead of a DOM element:
<script setup>
import { useTemplateRef } from 'vue'
import LoginForm from './LoginForm.vue'
const loginForm = useTemplateRef('form')
</script>
<template>
<LoginForm ref="form" />
<button @click="loginForm.reset()">Start over</button>
</template>
If LoginForm uses <script setup>, that click fails. loginForm.value exists, but reset isn’t on it.
Closed by default, and defineExpose
A component written with <script setup> is closed by default. None of its internal variables or functions are visible to a parent holding a ref to it. This is deliberate. A component’s real interface is its props, events, and slots. If parents could reach into any internal variable, every refactor of the child would risk breaking a parent somewhere.
When a parent genuinely needs to trigger something imperative, the child opts in with the defineExpose macro:
<!-- LoginForm.vue -->
<script setup>
import { ref, useTemplateRef } from 'vue'
const email = ref('')
const password = ref('')
const emailEl = useTemplateRef('email-field')
function reset() {
email.value = ''
password.value = ''
}
function focus() {
emailEl.value?.focus()
}
defineExpose({ reset, focus })
</script>
<template>
<form>
<input ref="email-field" v-model="email" />
<input v-model="password" type="password" />
</form>
</template>
Now the parent can call loginForm.value.reset() and loginForm.value.focus(), and nothing else. email and password stay private. Refs you expose are unwrapped on the instance, just like on a normal component instance, so an exposed count ref is read as loginForm.value.count, not loginForm.value.count.value. defineExpose must be called before any await in setup, or the properties exposed after it won’t be accessible. Typing a component ref so the parent knows what was exposed is covered in TypeScript with Vue.
React’s equivalent is a ref passed to the child together with useImperativeHandle, covered in direct DOM access with refs. Both frameworks make imperative access something the child opts into, not the default.
Use sparingly
Exposed methods are an escape hatch, like template refs themselves. Good uses are actions that don’t correspond to state: focus(), scrollToTop(), play(), or validate() on submit. If the parent is effectively setting the child’s state, such as childRef.value.open = true, that’s a prop or v-model in disguise, and it hides data flow the template should show. Props down, events up remains the default. defineExpose is for the cases that pattern can’t express cleanly. Component libraries use it this way: a form exposes validate(), a popover exposes open() and close(). Custom directives are another option for reusable DOM-level behaviour.
What the video covers
Alexander Lichter’s video is about the second half of this lesson. It explains why <script setup> components are closed by default, shows how defineExpose opens a deliberate public surface to a parent’s template ref, walks through real examples from component libraries, and discusses when not to use it. It assumes you already know how template refs work. Element refs, useTemplateRef, the null-until-mount rule, refs in v-for, and function refs are covered above in prose. The useTemplateRef chapter of his “5 Vue features” video (from 9:58) covers the 3.5 API, and LearnVue’s short video shows the template-ref basics in the pre-3.5 style.
Check yourself
Why does `const input = useTemplateRef('search'); input.value.focus()` at the top level of `<script setup>` throw, and where should the call go?
Setup runs before the template is rendered, so the `<input ref="search">` element doesn't exist yet and `input.value` is `null`. Move the call into `onMounted(() => input.value.focus())`, or into an event handler that runs after mount.
A parent holds a template ref to a `<script setup>` child and calls `childRef.value.reset()`, but gets 'reset is not a function'. The child does define `reset`. Why?
Components written with `<script setup>` are closed by default: none of their internal bindings are visible through a template ref. The child has to opt in with `defineExpose({ reset })`, and that call must come before any `await` in its setup.
You put `ref="items"` on an `<li v-for="item in list">`. What does the template ref hold, and what shouldn't you assume about it?
It holds an array of the rendered `<li>` elements once mounted. You shouldn't assume the array is in the same order as `list`. If you need a mapping from item to element, use a function ref that stores each element under the item's id.
When is exposing a method on a child component the wrong tool?
When the parent is really changing the child's state or reacting to something in it. That should be a prop the parent controls or an event the child emits, which keeps data flow declarative and visible in the template. Exposed methods are best kept for imperative actions that don't map to state, like `focus()`, `scrollToTop()`, or validating a form on submit.
Go deeper
Notes
Notes are saved to your account.
Everything else on this page works without one — progress and bookmarks keep themselves in this browser and come with you when you sign in. Notes are the one thing worth not trusting to a browser you might clear.
Your notes could not be loaded.