🎓 A1Learner
🔍
0 of 50 lessons completed

The onMounted Hook

The onMounted hook runs a function after Vue draws the component for the first time. onMounted is the hook for work that needs the page to exist first.

Register the hook

The hook sets message to Loaded once mounting is done.

onMounted(() => {
  message.value = 'Loaded!'
})

The starting value

The first render still shows Loading.

<p>{{ message }}</p>

Example

<script setup>
import { ref, onMounted } from 'vue'
const message = ref('Loading...')
onMounted(() => {
  message.value = 'Loaded!'
})
</script>
<template>
  <div>
    <p>{{ message }}</p>
  </div>
</template>

Key points

  • onMounted takes one function, and Vue calls it after mounting.
  • The hook runs once, right after the first draw.
  • It is the right place for start-up work that must wait for the first draw.
  • The hook does not run during a static render, so the first output shows the starting value.
  • A ref changed inside the hook updates the page after mounting.

In this example, message is a ref with the value Loading. onMounted registers a function that sets message to Loaded. The hook does not run in a static render, so the stated output shows Loading. After mounting in a live app, the hook runs and the page shows Loaded. A verified variant with message set to Loaded shows the post-mount render.

Note

Import onMounted from vue before calling it.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

When does onMounted run?