Performance: Effective scope for cleanup
This concept affects how efficiently Vue components release resources and avoid memory leaks, impacting long-term page responsiveness and stability.
import { onMounted, onUnmounted } from 'vue'; onMounted(() => { window.addEventListener('resize', onResize); }); onUnmounted(() => { window.removeEventListener('resize', onResize); });
import { onMounted } from 'vue'; onMounted(() => { window.addEventListener('resize', onResize); }); // No cleanup on unmount
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| No cleanup of event listeners | No direct DOM ops | 0 | 0 | [X] Bad |
| Cleanup in onUnmounted hook | No direct DOM ops | 0 | 0 | [OK] Good |
onMounted runs when the component appears, onUnmounted runs when it disappears.onUnmounted is the right hook.onUnmounted -> Option Csetup() using the onUnmounted hook?onUnmounted are functions that take a callback to run on that event.onUnmounted with a function: onUnmounted(() => { ... }). Other options misuse assignment or methods.setup() {
const timer = setInterval(() => console.log('tick'), 1000)
onUnmounted(() => clearInterval(timer))
}clearInterval(timer) stops the interval, so logging stops after unmount.setup() {
const timer = setInterval(() => console.log('tick'), 1000)
onMounted(() => clearInterval(timer))
}onMounted to clear interval means it stops immediately after mounting, so no ticks happen.onUnmounted is the correct hook to clear the timer.setup(). Which pattern correctly ensures the subscription is cleaned up only when the component unmounts?setup() {
const socket = new WebSocket('wss://example.com')
socket.onmessage = (event) => console.log(event.data)
// What cleanup code and where?
}onUnmounted(() => socket.close()).Pass the test and this pattern moves unknown