Lifecycle hooks let you run code at specific stages of a component's life — from creation to destruction.
import {
onMounted,
onUpdated,
onUnmounted,
onBeforeMount,
onBeforeUpdate,
onBeforeUnmount,
} from 'vue'
export default {
setup() {
onBeforeMount(() => {
console.log('Before component is mounted')
})
onMounted(() => {
console.log('Component mounted — DOM is ready')
// fetch initial data, set up event listeners, init third-party libs
})
onUpdated(() => {
console.log('Component updated — reactive data changed')
})
onBeforeUnmount(() => {
console.log('Before component is destroyed')
// clean up: remove event listeners, clear timers
})
onUnmounted(() => {
console.log('Component destroyed')
})
}
}
// Fetch data on mount
onMounted(async () => {
users.value = await fetchUsers()
})
// Set up and tear down a resize listener
onMounted(() => {
window.addEventListener('resize', handleResize)
})
onUnmounted(() => {
window.removeEventListener('resize', handleResize)
})
// Start and clear a timer
onMounted(() => {
timer = setInterval(tick, 1000)
})
onUnmounted(() => {
clearInterval(timer)
})