Performance: onMounted and onUnmounted
These lifecycle hooks affect the timing of DOM interactions and resource cleanup, impacting rendering responsiveness and memory usage.
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 |
|---|---|---|---|---|
| Add event listener in onMounted only | 1 addEventListener | 0 reflows | 0 paint | [X] Bad |
| Add in onMounted and remove in onUnmounted | 1 addEventListener + 1 removeEventListener | 0 reflows | 0 paint | [OK] Good |
onMounted lifecycle hook in Vue?onMountedonMounted hook runs after the component is inserted into the DOM and visible to the user.onUnmounted runs before removal, and creation hooks run earlier. Updating data is reactive and not tied to onMounted.onUnmounted in a Vue 3 component with Composition API?onUnmounted is a function that takes a callback function as an argument, so it must be called with parentheses and a function inside.onUnmounted with an arrow function. Options B, C, and D have invalid syntax or missing parentheses.import { ref, onMounted, onUnmounted } from 'vue'
export default {
setup() {
const count = ref(0)
let timer
onMounted(() => {
timer = setInterval(() => {
count.value++
}, 1000)
})
onUnmounted(() => {
clearInterval(timer)
})
return { count }
}
}count when the component is removed from the page?count every second when the component mounts.clearInterval(timer) when the component unmounts, stopping the increments.import { ref, onMounted, onUnmounted } from 'vue'
export default {
setup() {
const message = ref('Hello')
onMounted(() => {
console.log(message.value)
})
onUnmounted(() => {
console.log('Goodbye')
})
onMounted(() => {
console.log('Another mount')
})
return { message }
}
}onMounted hooks inside the same setup function; they run in the order declared.onUnmounted to be before onMounted, and message can be declared outside hooks.onMounted and onUnmounted to achieve this?import { onMounted, onUnmounted } from 'vue'
export default {
setup() {
let socket
// What should go here?
return {}
}
}onMounted) and cleaned up before it disappears (onUnmounted).onMounted to open and onUnmounted to close the socket. Other options misuse lifecycle hooks or open/close at wrong times.Pass the test and this pattern moves unknown