Skip to content
Tutorials Center
My learning

Topics

Lesson 30 of 87 ยท Components

Template Refs and Exposing Methods

Reach DOM elements and child components from code with Vue template refs. Learn when refs are available, refs inside v-for, function refs and how defineExpose limits the public API.

Vue's rule of thumb is that you describe the page with a template and let the framework update the DOM. Most of the time you never touch an element directly. But a few jobs cannot be expressed as data: focusing an input, selecting its text, scrolling an element into view, measuring a box, or starting a method on a child component such as a video player's play(). For those jobs Vue gives you template refs: a way to get hold of the real DOM element or the child component instance.

This lesson explains the ref attribute and the useTemplateRef() helper, why the ref is empty until the component is mounted, how refs behave inside v-for, how a child component decides what it shows to its parent through defineExpose, and what a function ref is. It builds on Reactive State with ref and Lifecycle Hooks, and pairs with Slots and Events and emits as ways for components to talk to each other.

The live examples use template strings, with the full browser build of Vue 3.5.13 (the one containing the template compiler) loaded from jsDelivr. The same code in a .vue file is shown read-only where it helps. useTemplateRef() needs Vue 3.5 or later; on older versions you declare a ref with the same name as the attribute instead, and both styles are demonstrated below.

Getting an element

Put the attribute ref="name" on an element, then ask Vue for it. In Vue 3.5 and later the recommended way is useTemplateRef('name'), which returns a ref that holds the element:

HTML
<!-- Read-only SFC -->
<script setup>
import { useTemplateRef, onMounted } from 'vue'

const input = useTemplateRef('my-input')

onMounted(() => {
  input.value.focus()
})
</script>

<template>
  <input ref="my-input" />
</template>

The ref is null until the element exists. During setup() and the first render, nothing has been created yet, so reading input.value there gives null. The earliest safe moment is onMounted. After that, the ref follows the element: if the element is removed (for example by a v-if), the ref becomes null again.

flowchart LR
  A["setup() runs<br/>ref = null"] --> B["first render<br/>DOM created"]
  B --> C["onMounted<br/>ref = element"]
  C -->|"v-if turns false"| D["element removed<br/>ref = null"]

A template ref is empty before mount and empty again after the element is removed, so guard against null.

Optional chaining is a cheap safeguard: input.value?.focus(). If the element is under a v-if that may be false, always use it.

Focus and select with a template ref

Treat refs as an escape hatch. Do not use them to change text, classes or visibility of elements that Vue renders: put that into reactive state and let the template do it. Direct DOM edits on elements Vue manages can be overwritten on the next update. Use refs for actions the browser exposes as methods (focus, select, scrollIntoView, play) and for reading measurements.

Refs inside v-for

A ref on an element inside v-for collects all the elements into an array. The array is filled during mount, and its order does not necessarily match the order of the source list (it can change after the list is reordered), so never rely on the index of a ref to identify an item. If you need the pairing, use a function ref or a data-id attribute.

This example declares a classic ref([]) whose name matches the ref="fields" attribute (this style also works on Vue 3.4 and earlier):

A template ref inside v-for

Function refs

Instead of a string, :ref can be bound to a function. Vue calls it with the element when it is created and with null when it is removed. This gives you full control: you can store the element in a Map under a key, run setup code when it appears, or clean up when it leaves. Because the function receives the element for each item separately, it is the reliable way to link a list item to its element.

A function ref with a Map

Remove the first task and press Show the Map: only the second task is left. The function ref received null for the removed element, which is the moment to delete your stored reference.

Two rules follow from how Vue calls function refs. First, Vue calls the function on every update of that element, not only on mount, and it calls it with null when the element goes away. Second, the function runs as part of rendering, so it must not change reactive state that the template reads. If it did (for example by pushing into a reactive log that the template displays), each render would trigger another render and Vue would stop with a "Maximum recursive updates exceeded" error. That is why the example above keeps its call log in a plain array and shows it only when you press a button.

Refs on child components

When you put ref on a component, the ref holds the component instance instead of an element. That lets the parent call the child's methods or read its state. This is useful for imperative widgets (player.play(), form.validate()), but it couples the two components tightly, so prefer props and events when they are enough (Events and emits).

A component using <script setup> is closed by default: the parent's ref does not see its variables. The child opts in to a public API with defineExpose:

HTML
<!-- FancyCounter.vue (read-only) -->
<script setup>
import { ref } from 'vue'

const count = ref(0)
const secret = 'internal detail'

function reset() {
  count.value = 0
}

defineExpose({ count, reset })
</script>

In a setup() function, the equivalent is calling expose({ count, reset }) from the second argument, as the live example does. A component using the Options API is open by default; add an expose option to restrict it.

flowchart LR
  P["Parent<br/>ref='counter'"] -->|"counter.value.reset()"| E["Exposed API<br/>count, reset"]
  subgraph Child["FancyCounter"]
    E
    X["private: secret"]
  end
  P -. "not reachable" .-> X

The parent's ref reaches only what the child exposes. Everything else stays private.

defineExpose limits what a parent can reach

Click the counter a few times, then press Reset from the parent and Inspect the child: the parent can reach count and reset, but secret is undefined from its point of view because it was not exposed.

Triggering a click or focus when the page loads

Because refs are filled at mount, onMounted is the place to act on an element as soon as the view appears: focus a field, or run the handler of a button as if the user had pressed it.

Click a button programmatically on load

The button already reads "Clicked 1 time(s)" when the page appears, because click() dispatched a real click event that the @click listener handled. If you only need the code the click would run, call that function directly instead of going through the DOM.

Tips and pitfalls

  • A ref on a component inside v-for collects component instances in an array, with the same ordering caveat as elements.
  • A component's root element is available as $el on the instance, but it is better to expose an explicit method than to rely on internals.
  • Refs are filled after render. If you change state and then immediately read the DOM through a ref, the DOM has not updated yet: wait with await nextTick() (DOM Update Timing and nextTick).
  • Do not call defineExpose after an await in <script setup>; call it before any awaited code.
  • Prefer exposing a few methods (focus, reset, validate) over exposing raw state that the parent could then mutate.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In setup() you read input.value of a template ref on the very first line. What do you get?

    Template refs are filled after the component is mounted. Read them in onMounted or in event handlers that run later.
  2. 2. What does a ref on an element inside v-for give you?

    Vue collects all elements into an array. If you need a reliable link between item and element, use a function ref.
  3. 3. A child uses <script setup> and a parent has ref="child" on it. What can the parent access via child.value?

    <script setup> components are closed by default. defineExpose (or expose() in setup()) chooses the public API.
  4. 4. When is a function ref called with null?

    Vue calls the function with the element on creation and with null on removal, which lets you clean up stored references.
  5. 5. Which task is a good use of a template ref?

    Focus is an imperative browser action with no declarative equivalent. Text, classes and visibility belong in reactive state and the template.

Summary

  • ref="name" plus useTemplateRef('name') (Vue 3.5+) or a same-named ref gives you the DOM element.
  • The ref is null before mount and after removal; read it in onMounted or later, and use ?. when the element is conditional.
  • A ref in v-for collects an array whose order is not guaranteed; use a function ref to pair items and elements.
  • A function ref receives the element, and null on removal.
  • A ref on a component holds its instance; <script setup> components expose nothing unless they call defineExpose.
  • Use refs for imperative actions and measurements, not for rendering.

Next, pull these ideas together in Designing Components.