0
0
Vueframework~30 mins

Effective scope for cleanup in Vue - Mini Project: Build & Apply

Choose your learning style9 modes available
Effective scope for cleanup in Vue 3
📋 What You'll Learn
💡 Why This Matters
🌍 Real World
Tracking window size is common in responsive web design to adjust layouts or load different components based on screen size.
💼 Career
Understanding lifecycle hooks and cleanup in Vue is essential for building efficient, bug-free applications that manage resources well.
Progress0 / 4 steps
1
Setup reactive window width
Create a Vue 3 component with setup() function. Inside it, create a ref called width and set it to window.innerWidth.
Vue
Hint

Use ref from Vue to create a reactive variable.

2
Add window resize event listener
Inside the setup() function, import and use onMounted. Add a window resize event listener that updates width.value to window.innerWidth when the window resizes.
Vue
Hint

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

3
Add cleanup with onUnmounted
Import onUnmounted and use it to remove the window resize event listener when the component unmounts. Store the event handler function in a variable called updateWidth so you can remove it properly.
Vue
Hint

Store the event handler in a variable so you can remove it later with removeEventListener.

4
Complete component with reactive display
Ensure the template displays the reactive width value inside a <div>. The component should update the displayed width as the window resizes and clean up the event listener on unmount.
Vue
Hint

The template should show the current window width reactively.