Using onMounted and onUnmounted in Vue 3
📖 Scenario: You are building a simple Vue 3 component that tracks how many seconds a user has spent on the page. When the component appears, it starts counting seconds. When the component is removed, it stops counting.
🎯 Goal: Create a Vue 3 component using the Composition API that starts a timer when the component is mounted and stops the timer when the component is unmounted. Display the seconds counted on the page.
📋 What You'll Learn
Use
ref to create a reactive variable called seconds initialized to 0Use
onMounted to start a timer that increments seconds every secondUse
onUnmounted to clear the timer when the component is removedDisplay the
seconds value inside a <div> element💡 Why This Matters
🌍 Real World
Timers and cleanup are common in web apps for animations, data fetching intervals, or user activity tracking.
💼 Career
Understanding lifecycle hooks like onMounted and onUnmounted is essential for building efficient Vue components that manage resources properly.
Progress0 / 4 steps