📖 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
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
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
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
Hint
Use mustache syntax {{ seconds }} inside a <div> to show the count.
Practice
(1/5)
1. What is the main purpose of the onMounted lifecycle hook in Vue?
easy
A. To run code when the component is destroyed
B. To run code before the component is created
C. To update the component's data reactively
D. To run code right after the component appears on the screen
Solution
Step 1: Understand the lifecycle timing of onMounted
The onMounted hook runs after the component is inserted into the DOM and visible to the user.
Step 2: Compare with other lifecycle hooks
onUnmounted runs before removal, and creation hooks run earlier. Updating data is reactive and not tied to onMounted.
Final Answer:
To run code right after the component appears on the screen -> Option D
Quick Check:
onMounted = runs after component appears [OK]
Hint: onMounted runs code after component shows up [OK]
Common Mistakes:
Confusing onMounted with onUnmounted
Thinking onMounted runs before creation
Assuming onMounted updates data reactively
2. Which of the following is the correct syntax to use onUnmounted in a Vue 3 component with Composition API?
easy
A. onUnmounted(() => { console.log('Component removed') })
B. onUnmounted = () => { console.log('Component removed') }
C. onUnmounted { console.log('Component removed') }
D. onUnmounted(function) { console.log('Component removed') }
Solution
Step 1: Recall the correct function call syntax
onUnmounted is a function that takes a callback function as an argument, so it must be called with parentheses and a function inside.
Step 2: Check each option's syntax
onUnmounted(() => { console.log('Component removed') }) correctly calls onUnmounted with an arrow function. Options B, C, and D have invalid syntax or missing parentheses.
Final Answer:
onUnmounted(() => { console.log('Component removed') }) -> Option A
Quick Check:
onUnmounted(callback) syntax correct [OK]
Hint: Use onUnmounted as a function with a callback [OK]
A. No error; multiple onMounted hooks are allowed and run in order
B. Multiple onMounted hooks are not allowed in the same setup
C. onUnmounted must be called before onMounted
D. message ref must be declared inside onMounted
Solution
Step 1: Check Vue 3 Composition API rules for lifecycle hooks
Vue 3 allows multiple onMounted hooks inside the same setup function; they run in the order declared.
Step 2: Verify other options
There is no requirement for onUnmounted to be before onMounted, and message can be declared outside hooks.
Final Answer:
No error; multiple onMounted hooks are allowed and run in order -> Option A
Quick Check:
Multiple onMounted hooks allowed [OK]
Hint: Multiple onMounted hooks run fine in setup [OK]
Common Mistakes:
Thinking only one onMounted hook is allowed
Believing lifecycle hooks must be in specific order
Assuming refs must be declared inside hooks
5. You want to create a Vue 3 component that starts a WebSocket connection when it appears and closes it when it disappears. Which is the best way to use onMounted and onUnmounted to achieve this?
import { onMounted, onUnmounted } from 'vue'
export default {
setup() {
let socket
// What should go here?
return {}
}
}
hard
A. Use onUnmounted to open the socket and onMounted to close it
B. Open the socket outside lifecycle hooks and close it inside onUnmounted
C. Use onMounted to open the socket and onUnmounted to close it
D. Open and close the socket both inside onMounted
Solution
Step 1: Understand lifecycle timing for resource management
Resources like WebSocket should be opened when the component appears (onMounted) and cleaned up before it disappears (onUnmounted).
Step 2: Match options with correct lifecycle usage
Use onMounted to open the socket and onUnmounted to close it correctly uses onMounted to open and onUnmounted to close the socket. Other options misuse lifecycle hooks or open/close at wrong times.
Final Answer:
Use onMounted to open the socket and onUnmounted to close it -> Option C
Quick Check:
Open onMounted, close onUnmounted for resources [OK]
Hint: Open resource onMounted, close onUnmounted [OK]
Common Mistakes:
Opening resource outside lifecycle hooks
Closing resource in onMounted instead of onUnmounted
Reversing open and close lifecycle hooks
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.