onMounted() signature and behavior
onMounted registers a callback to be called after the component has been mounted. Type: function onMounted(callback: () => void, target?: ComponentInternalInstance | null): void. A component is considered mounted after all of its synchronous child components have been mounted (does not include async components or components inside Suspense trees) and its own DOM tree has been created and inserted into the parent container. It only guarantees that the component's DOM tree is in-document if the application's root container is also in-document. This hook is typically used for performing side effects that need access to the component's rendered DOM, or for limiting DOM-related code to the client in a server-rendered application. This hook is not called during server-side rendering.
onMounted() example with template ref
Example showing onMounted accessing an element via template ref:
```vue
<script setup>
import { ref, onMounted } from 'vue'
const el = ref()
onMounted(() => {
el.value // <div>
})
</script>
<template>
<div ref="el"></div>
</template>
```
onUpdated() signature and behavior
onUpdated registers a callback to be called after the component has updated its DOM tree due to a reactive state change. Type: function onUpdated(callback: () => void, target?: ComponentInternalInstance | null): void. A parent component's updated hook is called after that of its child components. This hook is called after any DOM update of the component, which can be caused by different state changes. Multiple state changes can be batched into a single render cycle for performance reasons. If you need to access the updated DOM after a specific state change, use nextTick() instead. This hook is not called during server-side rendering. Do not mutate component state in the updated hook as this will likely lead to an infinite update loop.
onUpdated() example accessing updated DOM
Example showing onUpdated accessing updated DOM:
```vue
<script setup>
import { ref, onUpdated } from 'vue'
const count = ref(0)
onUpdated(() => {
// text content should be the same as current `count.value`
console.log(document.getElementById('count').textContent)
})
</script>
<template>
<button id="count" @click="count++">{{ count }}</button>
</template>
```
onUnmounted() signature and behavior
onUnmounted registers a callback to be called after the component has been unmounted. Type: function onUnmounted(callback: () => void, target?: ComponentInternalInstance | null): void. A component is considered unmounted after all of its child components have been unmounted and all of its associated reactive effects (render effect and computed/watchers created during setup()) have been stopped. Use this hook to clean up manually created side effects such as timers, DOM event listeners or server connections. This hook is not called during server-side rendering.
onUnmounted() example cleaning up timer
Example showing onUnmounted cleaning up a timer:
```vue
<script setup>
import { onMounted, onUnmounted } from 'vue'
let intervalId
onMounted(() => {
intervalId = setInterval(() => {
// ...
})
})
onUnmounted(() => clearInterval(intervalId))
</script>
```
onBeforeMount() signature and behavior
onBeforeMount registers a hook to be called right before the component is to be mounted. Type: function onBeforeMount(callback: () => void, target?: ComponentInternalInstance | null): void. When this hook is called, the component has finished setting up its reactive state, but no DOM nodes have been created yet. It is about to execute its DOM render effect for the first time. This hook is not called during server-side rendering.
onBeforeUpdate() signature and behavior
onBeforeUpdate registers a hook to be called right before the component is about to update its DOM tree due to a reactive state change. Type: function onBeforeUpdate(callback: () => void, target?: ComponentInternalInstance | null): void. This hook can be used to access the DOM state before Vue updates the DOM. It is also safe to modify component state inside this hook. This hook is not called during server-side rendering.
onBeforeUnmount() signature and behavior
onBeforeUnmount registers a hook to be called right before a component instance is to be unmounted. Type: function onBeforeUnmount(callback: () => void, target?: ComponentInternalInstance | null): void. When this hook is called, the component instance is still fully functional. This hook is not called during server-side rendering.
onErrorCaptured() signature and behavior
onErrorCaptured registers a hook to be called when an error propagating from a descendant component has been captured. Type: function onErrorCaptured(callback: ErrorCapturedHook): void, where ErrorCapturedHook = (err: unknown, instance: ComponentPublicInstance | null, info: string) => boolean | void. Errors can be captured from the following sources: component renders, event handlers, lifecycle hooks, setup() function, watchers, custom directive hooks, and transition hooks. The hook receives three arguments: the error, the component instance that triggered the error, and an information string specifying the error source type. In production, the 3rd argument (info) will be a shortened code instead of the full information string. The code to string mapping can be found in the Production Error Code Reference. You can modify component state in onErrorCaptured() to display an error state to the user. However, the error state should not render the original content that caused the error; otherwise the component will be thrown into an infinite render loop. The hook can return false to stop the error from propagating further.
onRenderTriggered() signature and behavior
onRenderTriggered registers a debug hook to be called when a reactive dependency triggers the component's render effect to be re-run. Type: function onRenderTriggered(callback: DebuggerHook): void, where DebuggerHook = (e: DebuggerEvent) => void and DebuggerEvent = { effect: ReactiveEffect, target: object, type: TriggerOpTypes (which is 'set' | 'add' | 'delete' | 'clear'), key: any, newValue?: any, oldValue?: any, oldTarget?: Map<any, any> | Set<any> }. This hook is development-mode-only and not called during server-side rendering.
onActivated() signature and behavior
onActivated registers a callback to be called after the component instance is inserted into the DOM as part of a tree cached by KeepAlive. Type: function onActivated(callback: () => void, target?: ComponentInternalInstance | null): void. This hook is not called during server-side rendering.
onDeactivated() signature and behavior
onDeactivated registers a callback to be called after the component instance is removed from the DOM as part of a tree cached by KeepAlive. Type: function onDeactivated(callback: () => void, target?: ComponentInternalInstance | null): void. This hook is not called during server-side rendering.
onServerPrefetch() signature and behavior
onServerPrefetch registers an async function to be resolved before the component instance is to be rendered on the server. Type: function onServerPrefetch(callback: () => Promise<any>): void. If the callback returns a Promise, the server renderer will wait until the Promise is resolved before rendering the component. This hook is only called during server-side rendering and can be used to perform server-only data fetching.
onServerPrefetch() example with client fallback
Example showing onServerPrefetch with a client-side fallback:
```vue
<script setup>
import { ref, onServerPrefetch, onMounted } from 'vue'
const data = ref(null)
onServerPrefetch(async () => {
// component is rendered as part of the initial request
// pre-fetch data on server as it is faster than on the client
data.value = await fetchOnServer(/* ... */)
})
onMounted(async () => {
if (!data.value) {
// if data is null on mount, it means the component
// is dynamically rendered on the client. Perform a
// client-side fetch instead.
data.value = await fetchOnClient(/* ... */)
}
})
</script>
```
Composition API lifecycle hooks must be called synchronously during setup()
All lifecycle hook APIs in the Composition API must be called synchronously during the setup() phase of a component. They cannot be called asynchronously or conditionally outside of the setup() function.
beforeCreate lifecycle hook
Called immediately when the instance is initialized and props are resolved. At this point, props are defined as reactive properties but state such as data() or computed has not yet been set up. The setup() hook of Composition API is called before beforeCreate().
created lifecycle hook
Called after the instance has finished processing all state-related options. When this hook is called, reactive data, computed properties, methods, and watchers have been set up. The mounting phase has not been started, and the $el property is not yet available.
beforeMount lifecycle hook
Called right before the component is to be mounted. The component has finished setting up its reactive state, but no DOM nodes have been created yet. It is about to execute its DOM render effect for the first time. This hook is not called during server-side rendering.
mounted lifecycle hook
Called after the component has been mounted. A component is considered mounted after all of its synchronous child components have been mounted (does not include async components or components inside Suspense trees) and its own DOM tree has been created and inserted into the parent container. This hook is typically used for performing side effects that need access to the component's rendered DOM, or for limiting DOM-related code to the client in a server-rendered application. Not called during server-side rendering.
beforeUpdate lifecycle hook
Called right before the component is about to update its DOM tree due to a reactive state change. This hook can be used to access the DOM state before Vue updates the DOM. It is safe to modify component state inside this hook. Not called during server-side rendering.
updated lifecycle hook
Called after the component has updated its DOM tree due to a reactive state change. A parent component's updated hook is called after that of its child components. This hook is called after any DOM update of the component, which can be caused by different state changes. Use nextTick() to access the updated DOM after a specific state change. Not called during server-side rendering. Do not mutate component state in the updated hook as this will likely lead to an infinite update loop.
beforeUnmount lifecycle hook
Called right before a component instance is to be unmounted. When this hook is called, the component instance is still fully functional. Not called during server-side rendering.
unmounted lifecycle hook
Called after the component has been unmounted. A component is considered unmounted after all of its child components have been unmounted and all of its associated reactive effects (render effect and computed/watchers created during setup()) have been stopped. Use this hook to clean up manually created side effects such as timers, DOM event listeners or server connections. Not called during server-side rendering.
errorCaptured lifecycle hook signature and behavior
Called when an error propagating from a descendant component has been captured. Type signature: errorCaptured?(this: ComponentPublicInstance, err: unknown, instance: ComponentPublicInstance | null, info: string): boolean | void. The hook receives three arguments: the error, the component instance that triggered the error, and an information string specifying the error source type. In production, the 3rd argument (info) will be a shortened code instead of the full information string. The hook can return false to stop the error from propagating further.
errorCaptured error sources
errorCaptured can capture errors from: component renders, event handlers, lifecycle hooks, setup() function, watchers, custom directive hooks, and transition hooks.
errorCaptured error propagation rules
By default, all errors are sent to app.config.errorHandler if defined. If multiple errorCaptured hooks exist on a component's inheritance chain or parent chain, all of them are invoked on the same error, in order of bottom to top (similar to DOM event bubbling). If errorCaptured itself throws an error, both this error and the original captured error are sent to app.config.errorHandler. An errorCaptured hook can return false to prevent the error from propagating further and to prevent any additional errorCaptured hooks or app.config.errorHandler from being invoked for this error.
errorCaptured caveat with async setup()
In components with async setup() function (with top-level await), Vue will always try to render the component template, even if setup() threw an error. This will likely cause more errors because the template might try to access non-existing properties of failed setup() context. When capturing errors in such components, be ready to handle errors from both failed async setup() (they will always come first) and failed render process.
renderTriggered lifecycle hook (dev-only)
Called when a reactive dependency triggers the component's render effect to be re-run. Type signature: renderTriggered?(this: ComponentPublicInstance, e: DebuggerEvent): void. DebuggerEvent has fields: effect (ReactiveEffect), target (object), type (TriggerOpTypes: 'set' | 'add' | 'delete' | 'clear'), key (any), newValue? (any), oldValue? (any), oldTarget? (Map<any, any> | Set<any>). This hook is development-mode-only and not called during server-side rendering.
deactivated lifecycle hook (KeepAlive)
Called after the component instance is removed from the DOM as part of a tree cached by KeepAlive. Not called during server-side rendering.
serverPrefetch lifecycle hook (SSR only)
Async function to be resolved before the component instance is to be rendered on the server. Type signature: serverPrefetch?(this: ComponentPublicInstance): Promise<any>. If the hook returns a Promise, the server renderer will wait until the Promise is resolved before rendering the component. Only called during server-side rendering and can be used to perform server-only data fetching.
serverPrefetch example
Example code showing serverPrefetch usage:
```js
export default {
data() {
return {
data: null
}
},
async serverPrefetch() {
// component is rendered as part of the initial request
// pre-fetch data on server as it is faster than on the client
this.data = await fetchOnServer(/* ... */)
},
async mounted() {
if (!this.data) {
// if data is null on mount, it means the component
// is dynamically rendered on the client. Perform a
// client-side fetch instead.
this.data = await fetchOnClient(/* ... */)
}
}
}
```
This example shows how to use serverPrefetch for server-side data fetching and mounted for client-side fallback.
onMounted hook for post-render code
The onMounted hook runs code after the component has finished the initial rendering and created the DOM nodes. It is one of the most commonly used lifecycle hooks.
Most commonly used lifecycle hooks
The most commonly used composition API lifecycle hooks are onMounted, onUpdated, and onUnmounted.
Lifecycle hooks must be registered synchronously
When calling onMounted or other lifecycle hooks, Vue automatically associates the registered callback function with the current active component instance. This requires these hooks to be registered synchronously during component setup. For example, calling onMounted inside a setTimeout will not work.
Lifecycle hooks do not need to be lexically inside setup()
While lifecycle hooks must be registered synchronously, the call does not need to be placed lexically inside setup() or <script setup>. onMounted() can be called in an external function as long as the call stack is synchronous and originates from within setup().
Avoid arrow functions when declaring options API lifecycle hooks
In the options API, all lifecycle hooks are called with their this context pointing to the current active instance invoking it. You should avoid using arrow functions when declaring lifecycle hooks, as you won't be able to access the component instance via this if you do so.
watchEffect() API creates a reactive effect
watchEffect() is a Vue API that allows you to create reactive effects. It automatically tracks dependencies accessed during its callback execution and re-runs the callback whenever those dependencies change.
onRenderTracked and onRenderTriggered lifecycle hooks
onRenderTracked() and onRenderTriggered() are composition API lifecycle hooks for debugging reactivity. onRenderTracked receives a debugger event with information about a dependency that was tracked during render. onRenderTriggered receives a debugger event with information about a dependency that triggered a re-render. Both hooks only work in development mode.
watch() and watchEffect() debugging with onTrack and onTrigger
Both watch() and watchEffect() support onTrack and onTrigger options. onTrack is called when a reactive property or ref is tracked as a dependency. onTrigger is called when a dependency mutation triggers the watcher. Both callbacks receive debugger events in the same format as component debug hooks. These options only work in development mode.