Cleaning up resources like timers or event listeners helps keep your app fast and bug-free. It stops things from running when they are no longer needed.
0
0
Effective scope for cleanup in Vue
Introduction
When you start a timer or interval inside a component
When you add event listeners to the window or document
When you subscribe to external data or services
When you want to avoid memory leaks in your app
When you want to reset or clear resources before a component is removed
Syntax
Vue
<script setup> import { onUnmounted } from 'vue' const timer = setInterval(() => { console.log('Tick') }, 1000) onUnmounted(() => { clearInterval(timer) }) </script>
onUnmounted runs cleanup code when the component is removed from the page.
Always pair setup code (like timers) with cleanup code to avoid leftover effects.
Examples
This example adds a click listener and removes it when the component unmounts.
Vue
<script setup> import { onUnmounted } from 'vue' const listener = () => console.log('Clicked') window.addEventListener('click', listener) onUnmounted(() => { window.removeEventListener('click', listener) }) </script>
This example updates a counter every second and stops the timer when the component is gone.
Vue
<script setup> import { ref, onUnmounted } from 'vue' const count = ref(0) const interval = setInterval(() => { count.value++ }, 1000) onUnmounted(() => { clearInterval(interval) }) </script>
Sample Program
This component shows seconds passed. It starts a timer when created and clears it when removed to stop counting.
Vue
<template>
<div>
<p>Seconds passed: {{ seconds }}</p>
</div>
</template>
<script setup>
import { ref, onUnmounted } from 'vue'
const seconds = ref(0)
const timer = setInterval(() => {
seconds.value++
}, 1000)
onUnmounted(() => {
clearInterval(timer)
console.log('Timer cleared on unmount')
})
</script>OutputSuccess
Important Notes
Always use onUnmounted to clean up side effects in Vue components.
Forgetting to clean up can cause bugs or slow down your app over time.
Cleanup functions run automatically when the component is removed from the page.
Summary
Use onUnmounted to run cleanup code in Vue components.
Cleanup stops timers, listeners, or subscriptions to keep your app healthy.
Always match setup code with cleanup to avoid memory leaks.