0
0
Vueframework~30 mins

Composable with lifecycle hooks in Vue - Mini Project: Build & Apply

Choose your learning style9 modes available
Composable with lifecycle hooks
📖 Scenario: You are building a Vue 3 app that needs to track the window width and update it reactively when the window is resized.
🎯 Goal: Create a composable function that uses Vue lifecycle hooks to track and update the window width reactively.
📋 What You'll Learn
Create a reactive variable to store the window width
Use the onMounted lifecycle hook to add a window resize event listener
Use the onUnmounted lifecycle hook to remove the event listener
Return the reactive window width variable from the composable
💡 Why This Matters
🌍 Real World
Tracking window size is common in responsive design to adapt UI elements dynamically.
💼 Career
Understanding composables and lifecycle hooks is essential for building maintainable Vue 3 applications.
Progress0 / 4 steps
1
Create a reactive variable for window width
Create a composable function called useWindowWidth that defines a reactive variable width initialized to window.innerWidth using Vue's ref.
Vue
Need a hint?

Use ref from Vue to create a reactive variable.

2
Add onMounted lifecycle hook to listen for resize
Inside the useWindowWidth function, import and use Vue's onMounted hook to add a resize event listener on window. The listener should update width.value to window.innerWidth.
Vue
Need a hint?

Use onMounted to add the event listener only after the component is mounted.

3
Add onUnmounted lifecycle hook to remove listener
Import Vue's onUnmounted hook and use it inside useWindowWidth to remove the resize event listener from window when the component unmounts. Store the listener function in a variable called updateWidth.
Vue
Need a hint?

Define the listener function separately so you can remove it later.

4
Return the reactive width variable
At the end of the useWindowWidth function, return an object with the width reactive variable so components can use it.
Vue
Need a hint?

Return the reactive variable inside an object for easy destructuring.