FrontendDeveloper.in

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 StageComposition API HookDescription
Before component creationonBeforeMount()Called right before the component is mounted
Component mountedonMounted()Called after the component has been mounted
Before updateonBeforeUpdate()Called before the component updates the DOM
After updateonUpdated()Called after the component updates the DOM
Before unmountonBeforeUnmount()Called right before the component is unmounted
Component unmountedonUnmounted()Called after the component is unmounted
Error capturedonErrorCaptured()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')
})
 }
 }
Back to all Vue.js questions
Get LinkedIn Premium at Rs 399