The process of a component from creation to destruction is called life cycle.
When we use the Vue3 combined API, there are no beforeCreate and created life cycles
The component life cycle is as follows:
- onBeforeMount() is called before the component DOM is actually rendered and mounted. At this step, the root element doesn't exist yet.
- onMounted() is called after the component's first render, the element is now available, allowing direct DOM access
- onBeforeUpdate() Called when the data is updated, before the virtual DOM is patched.
- onUpdated() After the DOM is updated, the updated method will be called.
- onBeforeUnmount() Called before the component instance is unmounted. At this stage, the instance is still fully functional.
- onUnmounted() Called after the component instance is unmounted. When this hook is called, all directives of the component instance are unbound, all event listeners are removed, and all child component instances are unmounted.
Options API vs Composition API hooks
Optional API | Composite API |
---|---|
beforeCreate | Not needed* |
created | Not needed* |
beforeMount | onBeforeMount |
mounted | onMounted |
beforeUpdate | onBeforeUpdate |
updated | onUpdated |
beforeUnmount | onBeforeUnmount |
unmounted | onUnmounted |
errorCaptured | onErrorCaptured |
renderTracked | onRenderTracked |
renderTriggered | onRenderTriggered |
activated | onActivated |
deactivated | onDeactivated |
Code example:
<template>
<h3>我是组件</h3>
<div ref="div">{
{str}}</div>
<button @click="change">修改str</button>
</template>
<script setup lang="ts">
import {
ref,onBeforeMount,onMounted,onBeforeUpdate,onUpdated,onBeforeUnmount,onUnmounted } from 'vue';
const str=ref<string>('我是大漂亮');
console.log(str);
const div=ref<HTMLDivElement>();
const change=()=>{
str.value='小可爱';
}
onBeforeMount(()=>{
console.log('创建前',div.value);
})
onMounted(()=>{
console.log('挂载完成',div.value);
})
onBeforeUpdate(()=>{
console.log('更新前')
})
onUpdated(()=>{
console.log('更新完成')
})
onBeforeUnmount(()=>{
console.log('卸载之前')
})
onUnmounted(()=>{
console.log('卸载完成')
})
</script>
<style scoped>
</style>
Page loading completed:
Ref<"I'm Damei">
was undefined before creation and the mount
was completed
<div>小可爱</div>"
After clicking the button:
Console printing:
before update,
update complete