0
0
Vueframework~30 mins

Lifecycle hooks in Composition API in Vue - Mini Project: Build & Apply

Choose your learning style9 modes available
Lifecycle hooks in Composition API
📖 Scenario: You are building a simple Vue 3 component that shows a message and logs lifecycle events to the console. This helps you understand when the component is created, mounted, updated, and unmounted.
🎯 Goal: Create a Vue 3 component using the Composition API that uses lifecycle hooks onMounted, onUpdated, and onUnmounted to log messages to the console when these events happen.
📋 What You'll Learn
Create a Vue 3 component using <script setup>
Use the Composition API lifecycle hooks onMounted, onUpdated, and onUnmounted
Log specific messages to the console inside each lifecycle hook
Display a simple message in the template
💡 Why This Matters
🌍 Real World
Understanding lifecycle hooks helps developers run code at specific times in a component's life, such as fetching data when a component appears or cleaning up resources when it disappears.
💼 Career
Many Vue.js jobs require knowledge of lifecycle hooks to manage component behavior, optimize performance, and handle side effects properly.
Progress0 / 4 steps
1
Create the basic Vue component structure
Create a Vue 3 component using <script setup> and add a <template> section that displays the text "Hello from Lifecycle Demo" inside a <div>.
Vue
Need a hint?

Start by writing the template with a div and the exact text. Then add an empty <script setup> block.

2
Import lifecycle hooks
Inside the <script setup>, import the lifecycle hooks onMounted, onUpdated, and onUnmounted from 'vue'.
Vue
Need a hint?

Use ES module import syntax to import the three lifecycle functions from 'vue'.

3
Add lifecycle hooks with console logs
Use the imported lifecycle hooks inside <script setup> to log these exact messages to the console:
- In onMounted, log "Component mounted"
- In onUpdated, log "Component updated"
- In onUnmounted, log "Component unmounted"
Vue
Need a hint?

Call each lifecycle hook function with an arrow function that calls console.log with the exact message.

4
Add a reactive counter and update log
Inside <script setup>, create a reactive variable called count initialized to 0 using ref from 'vue'. Add a button in the template that increments count when clicked. The onUpdated hook should log the updated count value with the message "Component updated: count is X" where X is the current count.
Vue
Need a hint?

Import ref from 'vue'. Use const count = ref(0). Add a button with @click="count++". Update the onUpdated hook to log the count value using a template string.