Lifecycle and Template Refs

By Syncfusion®, Inc. · Last updated

The life of a component from creation to mount, update and unmount, the Composition API lifecycle hooks with an Options API mapping, template refs with useTemplateRef(), refs inside v-for, component refs and defineExpose(), and common uses: DOM access, listeners, timers, requests and cleanup.

The Life of a Component

  • A component is born, shown, updated and finally removed.
  • These stages are its lifecycle.
  • Lifecycle hook = a function Vue calls at one stage, such as "just shown".
  • You use hooks to start and stop work that lives outside Vue: timers, listeners and requests.

Simple lesson: hooks let you run code when a component appears, changes or leaves.

A Real-World Example

  • Meera's kitchen screen shows how long an order has been waiting.
  • The timer must start when the order card appears.
  • When the order is served, the card goes away. The timer must stop too.
  • What happened: onMounted started the timer once the card was on the page.
  • "Serve the order" removed the card. onUnmounted stopped the timer.

What You Will Learn

  1. The four stages of a component's life.
  2. The Composition API hooks, and their Options API names.
  3. When each hook runs.
  4. How to reach a DOM element with a template ref.
  5. How to collect refs inside v-for.
  6. How to call a child component's functions.
  7. How defineExpose() decides what a parent may use.
  8. Common jobs for hooks, and how to clean up.

Lifecycle Stages

Animation: a dot moves along the lifecycle. Setup, before mount, mounted, then a loop of before update and updated, then before unmount and unmounted

setup onBeforeMount onMounted onBeforeUpdate onUpdated onBeforeUnmount onUnmounted

state changes: repeat

Created → shown → updated (many times) → removed

A component is set up, mounted, updated many times, then unmounted.

  • Setup = <script setup> runs. State is created. Nothing is on the page yet.
  • Mount = Vue builds the elements and puts them on the page.
  • Update = state changed, so Vue updates the page.
  • Unmount = the component is removed, for example by v-if.
  • What happened: the Console shows steps 1 to 3 at the start.
  • Each like shows 4 and 5. "Remove" shows 6 and 7.

Hooks in the Options API

  • Older code uses the Options API names. You will learn that style in Options API.
Composition APIOptions APIRuns
<script setup> itselfbeforeCreate, createdBefore anything is on the page
onBeforeMountbeforeMountJust before the first render
onMountedmountedAfter the elements are on the page
onBeforeUpdatebeforeUpdateBefore the page is updated
onUpdatedupdatedAfter the page is updated
onBeforeUnmountbeforeUnmountBefore removal
onUnmountedunmountedAfter removal

Call hooks at the top level of <script setup>, never later inside a setTimeout or after an await. Vue must know which component a hook belongs to when it is registered.

Simple lesson: onMounted to start, onUnmounted to clean up.

Template Refs

  • Sometimes you need the real DOM element: to focus a box, measure a size or call a browser API.
  • Give the element a ref="name" attribute.
  • In the script, useTemplateRef("name") (Vue 3.5) gives you a ref to it.
  • It is null until the component is mounted. Use it in onMounted or later.
  • Code written before Vue 3.5 uses const box = ref(null) with the same name as ref="box". It does the same job.

Before Vue 3.5, code used a plain ref with the same name: const searchBox = ref(null) with ref="searchBox". You will still see this in older projects. It works the same way.

Refs Inside v-for

  • A ref inside v-for gives an array of elements.
  • The order of the array may not match the order of the list. Use it for counting or looping, not by position.

Component Refs and defineExpose()

  • A ref on a component gives you that component's instance.
  • With <script setup>, a component is closed by default. The parent sees nothing inside.
  • The child chooses what to share with defineExpose({ ... }).
  • Use this rarely. Props and events are usually the better way.
  • What happened: the parent called reset() and read plates.
  • secret was not exposed, so the parent cannot see it.

Simple lesson: ref + useTemplateRef() reach elements and components. defineExpose() decides what a child shares.

Common Jobs for Hooks

JobStart inClean up in
Focus or measure an elementonMountedNothing
Listen to window or documentonMountedonUnmounted (remove the listener)
Timers: setInterval, setTimeoutonMountedonUnmounted (clear it)
Load data from a serveronMounted or <script setup>onUnmounted (abort the request)
A third-party chart or maponMountedonUnmounted (destroy it)

Close the panel quickly, before the dishes load. The Console shows "Request cancelled", because onUnmounted aborted it.

Simple lesson: whatever you start in a hook, stop in onUnmounted.

TL;DR

  • Lifecycle = setup → mount → update (many times) → unmount.
  • onMounted = the elements are on the page. Start DOM work, timers, listeners.
  • onUpdated = the page shows the new state.
  • onUnmounted = clean up timers, listeners and requests.
  • Options names = mounted, updated, unmounted ...
  • Template ref = ref="name" + useTemplateRef("name").
  • Refs in v-for = an array of elements.
  • Component ref = the child's instance. Closed by default.
  • defineExpose() = what a child shares with a parent's ref.

Common mistakes

MistakeWrong ideaCorrect ideaWhat goes wrong
Using a template ref in setupThe element exists at onceUse it in onMounted or laterIt is null
No cleanup for timersVue stops themclearInterval in onUnmountedTimers keep running after the component is gone
Hook after awaitHooks work anywhereRegister hooks at the top levelA warning, and the hook never runs
Changing state in onUpdatedIt is a good place to fix valuesUse computed or a watcherAn endless update loop
Reading a child's state without defineExposeParents see everythingExpose what is neededThe value is undefined
Refs in v-for by positionThe order matches the listUse them as an unordered setThe wrong element is changed

Check Yourself

Exercises

What to Remember

  • Components go through setup, mount, update and unmount.
  • Start DOM work in onMounted. Clean everything up in onUnmounted.
  • Register hooks at the top level of <script setup>.
  • ref="name" + useTemplateRef("name") reaches elements after mount.
  • Component refs see only what defineExpose() shares.

Next: Options API