首先在Vue3.0中, 生命周期钩子都应该在setup()阶段被调用.
其次为了更好地语义化, 将beforeDestroy、destroyed两个生命周期替换为: beforUnmount、unmounted.
而Vue3.0新增的钩子通过在生命周期函数前加on来访问组件的生命周期, 一下是Vue2.0与Vue3.0 生命周期钩子的对应关系:
beforeCreated() --> use setup()
created() --> use setup()
beforeMount() --> onBeforeMount()
mounted() --> onMounted()
beforeUpdate() --> onBeforeUpdate()
updated() --> onUpdated()
beforeDestroy() --> onBeforeUnmount()
destroyed() --> onUnmounted()
activated() --> onActivated()
deactivated() --> onDeactivated()
errorCaptured() --> onErrorCaptured()
此外Vue3.0 还新增了两个生命周期: onRenderTracked、onRenderTriggered
接下来用表格更直观的展示每个生命周期都做了什么:
Vue2.0 | Vue3.0 | Description |
beforeCreated | use setup | 组件实例刚被创建, 组件属性计算之前, 如data |
created | use setup | 组件实例创建完成, 属性已绑定,但DOM还未生成 |
beforeMount | onBeforeMount | 模板编译 / 挂载之前 |
mounted | onMounted | 模板编译 / 挂载之后 |
beforeUpdate | onBeforeUpdate | 组件更新之前 |
updated | onUpdated | 组件更新之后,不要在此状态下更改组件!会导致无限循环 |
activated | onActivated | for keep-alive, 组件被激活时调用 |
deactivated | onDeactivated | for keep-alive, 组件被移除时调用 |
beforeDestroy | onBeforeUnmount | 组件销毁前, 组件仍然可用 |
destroyed | onUnmounted | 组件销毁后, 解除所有绑定和子组件 |
errorCaptured | onErrorCaptured | 当捕获一个来自子孙组件的错误时调用 |
代码示例:
<template>
<img alt="Vue logo" src="./assets/logo.png">
<h1>{{ count }}</h1>
<h1>{{ double }}</h1>
<button @click="increase">👍+1</button>
</template>
<script lang="ts">
import { computed, reactive, toRefs, onMounted, onUpdated, onRenderTriggered, } from 'vue';
interface IDataProps {
count: number
double: number
increase: ()=> void
}
export default({
name: 'App',
components: {},
setup() {
const data: IDataProps = reactive({
count: 0,
increase: ()=>{ data.count++ },
double: computed(()=>data.count * 2)
})
onMounted(()=>{
console.log('mounted')
})
onUpdated(()=>{
console.log('updated')
})
onRenderTriggered((event)=>{
console.log(event)
})
const refData = toRefs(data)
return {
...refData
}
}
});
</script>
<style>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>