Vue.js question detail
What is watch() and how is it used?
In Composition API, lifecycle hooks are functions you call inside the setup() function to hook into different
stages of a component's lifecycle. These hooks replace the traditional options API lifecycle methods (like created(),
mounted(), etc.) with function-based hooks that are imported from Vue.
Main Lifecycle Hooks
| Lifecycle Stage | Composition API Hook | Description |
|---|---|---|
| Before component creation | onBeforeMount() | Called right before the component is mounted |
| Component mounted | onMounted() | Called after the component has been mounted |
| Before update | onBeforeUpdate() | Called before the component updates the DOM |
| After update | onUpdated() | Called after the component updates the DOM |
| Before unmount | onBeforeUnmount() | Called right before the component is unmounted |
| Component unmounted | onUnmounted() | Called after the component is unmounted |
| Error captured | onErrorCaptured() | Called when an error from a child component is captured |
| Activated (keep-alive) | onActivated() | Called when a kept-alive component is activated |
| Deactivated (keep-alive) | onDeactivated() | Called when a kept-alive component is deactivated |
The above hooks can be imported from vue and used inside setup() function. For example, the usage of hooks will be
as follows,
import {onMounted, onBeforeUnmount} from 'vue'
export default {
setup() {
onMounted(() => {
console.log('Component is mounted!')
})
onBeforeUnmount(() => {
console.log('Component is about to unmount')
})
}
}