0
0
Vueframework~30 mins

onMounted and onUnmounted in Vue - Mini Project: Build & Apply

Choose your learning style9 modes available
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 0
Use onMounted to start a timer that increments seconds every second
Use onUnmounted to clear the timer when the component is removed
Display 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
1
Set up the reactive seconds variable
Create a Vue 3 component with <script setup> and import ref from 'vue'. Then create a reactive variable called seconds and set it to 0.
Vue
Need a hint?

Use ref(0) to create a reactive number starting at zero.

2
Create a variable to hold the timer ID
Add a variable called timer and set it to null. This will hold the ID of the timer so you can clear it later.
Vue
Need a hint?

Use let to declare timer because it will change later.

3
Start the timer on mount and stop it on unmount
Import onMounted and onUnmounted from 'vue'. Use onMounted to start a timer that increases seconds.value by 1 every 1000 milliseconds and save the timer ID in timer. Use onUnmounted to clear the timer using clearInterval(timer).
Vue
Need a hint?

Use setInterval inside onMounted and clearInterval inside onUnmounted.

4
Display the seconds in the template
Add a <template> section with a <div> that shows the text Seconds: followed by the value of seconds. Use the Vue template syntax {{ seconds }} to display the reactive value.
Vue
Need a hint?

Use mustache syntax {{ seconds }} inside a <div> to show the count.