Skip to main content
Practice Problems

Template refs in Vue.js

What are Template Refs?

Template refs give you direct access to DOM elements or child component instances. They're declared using the ref attribute on elements and accessed via a ref() in script.


Basic DOM Ref

vue
<script setup> import { ref, onMounted } from 'vue' const inputRef = ref<HTMLInputElement | null>(null) onMounted(() => { // Element is available after mount inputRef.value?.focus() }) </script> <template> <input ref="inputRef" type="text" /> </template>

Component Ref

vue
<script setup> import { ref } from 'vue' import ChildComponent from './ChildComponent.vue' const childRef = ref<InstanceType<typeof ChildComponent> | null>(null) function callChild() { childRef.value?.someMethod() console.log(childRef.value?.someData) } </script> <template> <ChildComponent ref="childRef" /> <button @click="callChild">Call Child</button> </template>

Note: With <script setup>, child components must use defineExpose to make properties accessible via ref.

Refs in v-for

vue
<script setup> import { ref, onMounted } from 'vue' const itemRefs = ref<HTMLElement[]>([]) onMounted(() => { console.log(itemRefs.value.length) // Array of elements itemRefs.value[0]?.scrollIntoView() }) </script> <template> <ul> <li v-for="item in items" :key="item.id" ref="itemRefs"> {{ item.name }} </li> </ul> </template>

Function Refs

vue
<script setup> const elements = ref(new Map<string, HTMLElement>()) function setRef(el: HTMLElement | null, id: string) { if (el) elements.value.set(id, el) else elements.value.delete(id) } </script> <template> <div v-for="item in items" :key="item.id" :ref="(el) => setRef(el as HTMLElement, item.id)" > {{ item.name }} </div> </template>

Common Use Cases

Use CaseExample
Focus managementinputRef.value?.focus()
Scroll controlel.scrollIntoView()
Canvas drawingcanvasRef.value?.getContext('2d')
Third-party librariesInitialize chart on DOM element
Measure dimensionsel.offsetHeight, el.getBoundingClientRect()
Call child methodschildRef.value?.reset()

Important Rules

  • Refs are null before mount — access in onMounted or later
  • Refs are null if element is conditionally rendered (v-if="false")
  • With <script setup>, child components need defineExpose
  • Prefer reactive data over direct DOM manipulation

Important:

Template refs provide direct DOM access when you need it — for focus management, scrolling, measuring, canvas operations, or third-party library integration. They're null before mount and when the element is conditionally hidden. Always prefer Vue's reactive data model over direct DOM manipulation when possible.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.

Finished reading?
Practice Problems