onMounted runs?Consider a Vue 3 component that uses onMounted to log a message. What will you see in the browser console when the component first appears?
import { onMounted } from 'vue'; export default { setup() { onMounted(() => { console.log('Component is now mounted'); }); } }
Think about when onMounted runs in the component lifecycle.
onMounted runs once after the component is inserted into the DOM. It is perfect for running code that needs the component to be visible, like logging or fetching data.
onUnmounted in a Vue component?In a Vue 3 component, onUnmounted is used to clean up resources. What happens when the component is removed from the page?
import { onUnmounted } from 'vue'; export default { setup() { onUnmounted(() => { console.log('Component is now unmounted'); }); } }
Remember when onUnmounted runs in the component lifecycle.
onUnmounted runs once when the component is removed from the DOM. It is used to clean up things like timers or event listeners.
onMounted and onUnmounted in a Vue component?Given this Vue 3 component, what will the console show when the component is mounted and then unmounted?
import { ref, onMounted, onUnmounted } from 'vue'; export default { setup() { const count = ref(0); onMounted(() => { console.log('Mounted with count:', count.value); }); onUnmounted(() => { console.log('Unmounted with count:', count.value); }); return { count }; } }
Think about when each lifecycle hook runs and the initial value of count.
The onMounted hook runs once after mounting and logs the initial count value 0. The onUnmounted hook runs once after unmounting and logs the same count value.
onUnmounted callback never run?Look at this Vue 3 component. Why does the message inside onUnmounted never appear in the console?
import { onUnmounted } from 'vue'; export default { setup() { onUnmounted(() => { console.log('Component unmounted'); }); }, template: '<div>Test</div>' };
Think about when onUnmounted runs and what triggers it.
onUnmounted only runs when the component is removed from the DOM. If the component stays visible, the hook never triggers.
onMounted and onUnmounted help manage side effects in Vue 3?Which statement best explains the role of onMounted and onUnmounted in managing side effects like timers or event listeners?
Think about how to avoid leftover timers or listeners after a component is gone.
onMounted is used to start side effects safely after the component is visible. onUnmounted stops or cleans up those side effects to avoid memory leaks or errors.