Vue 3 Basic
What are Vue's lifecycle hooks?
What is the Lifecycle?
A Vue component's lifecycle refers to the entire process from creation to destruction. Vue automatically calls lifecycle hooks at different stages, allowing us to run custom logic at specific moments.
Vue 3 Lifecycle Hooks
| Hook | Description |
|---|---|
setup() |
Runs first; entry point for Composition API (replaces beforeCreate + created) |
onBeforeMount |
Before mounting; DOM has not been created yet |
onMounted |
After mounting; DOM is ready, ideal for API calls |
onBeforeUpdate |
Before reactive data updates trigger a re-render |
onUpdated |
After the DOM has been re-rendered |
onBeforeUnmount |
Before the component is destroyed; clean up timers and listeners here |
onUnmounted |
Component has been fully destroyed |
Vue 3 Composition API Usage
import { onMounted, onBeforeUnmount } from 'vue'
export default {
setup() {
onMounted(() => {
console.log('Component mounted, DOM is ready')
// fetch API data here
})
onBeforeUnmount(() => {
console.log('Cleaning up before unmount')
// clearInterval, removeEventListener, etc.
})
}
}
Vue 2 vs Vue 3 Comparison
| Vue 2 | Vue 3 (Composition API) |
|---|---|
beforeCreate |
Replaced by setup() |
created |
Replaced by setup() |
beforeMount |
onBeforeMount |
mounted |
onMounted |
beforeUpdate |
onBeforeUpdate |
updated |
onUpdated |
beforeDestroy |
onBeforeUnmount |
destroyed |
onUnmounted |
Common Interview Points
- Most used hooks:
onMounted(API calls, DOM access) andonBeforeUnmount(cleanup) - Parent-child order: parent beforeMount → child mounted → parent mounted
✦ AI Mock Interview
Type your answer and get instant AI feedback
Sign in to use AI scoring
