We use onMounted to run code right after a component appears on the screen. We use onUnmounted to run code just before the component disappears. This helps manage tasks like starting and stopping timers or event listeners.
0
0
onMounted and onUnmounted in Vue
Introduction
You want to fetch data from a server as soon as a component shows up.
You need to start a timer or animation when a component appears.
You want to clean up event listeners or timers when a component is removed.
You want to log or track when a component is created and destroyed.
You need to set up or tear down subscriptions or connections tied to the component.
Syntax
Vue
import { onMounted, onUnmounted } from 'vue'; export default { setup() { onMounted(() => { // code to run when component mounts }); onUnmounted(() => { // code to run when component unmounts }); } }
onMounted and onUnmounted are called inside the setup() function.
They take a function as an argument, which runs at the right time.
Examples
This example logs a message when the component appears.
Vue
import { onMounted } from 'vue'; export default { setup() { onMounted(() => { console.log('Component is now visible'); }); } }
This example logs a message just before the component disappears.
Vue
import { onUnmounted } from 'vue'; export default { setup() { onUnmounted(() => { console.log('Component is about to be removed'); }); } }
This example starts a timer when the component mounts and stops it when it unmounts.
Vue
import { onMounted, onUnmounted, ref } from 'vue'; export default { setup() { const timer = ref(null); onMounted(() => { timer.value = setInterval(() => { console.log('Tick'); }, 1000); }); onUnmounted(() => { clearInterval(timer.value); console.log('Timer stopped'); }); } }
Sample Program
This Vue component logs a message when it appears, starts a timer that logs every second, and cleans up the timer with a message when it disappears.
Vue
<template>
<div>
<p>Check the console for messages.</p>
</div>
</template>
<script setup>
import { onMounted, onUnmounted, ref } from 'vue';
const timer = ref(null);
onMounted(() => {
console.log('Component mounted');
timer.value = setInterval(() => {
console.log('Timer tick');
}, 1000);
});
onUnmounted(() => {
clearInterval(timer.value);
console.log('Component unmounted and timer cleared');
});
</script>OutputSuccess
Important Notes
Always clear timers or listeners in onUnmounted to avoid memory leaks.
You can use multiple onMounted or onUnmounted calls if needed.
Check browser console to see the logs when testing these hooks.
Summary
onMounted runs code right after the component appears.
onUnmounted runs code just before the component disappears.
Use them to start and stop tasks tied to the component's life.