我们知道,在每个组件在被创建时,要经过一系列的初始化过程,比如,需要设置数据监听、编译模板、实例挂载并在数据变化时触发DOM更新等。
在Vue2中提供了生命周期钩子函数,如beforeCreate 、created 、beforeMount 、mounted 、beforeUpdate、updated、beforeDestory、destoryed等,用于在组件不同阶段执行一些我们想要的执行的操作
到了Vue3,有所变化
beforeCreate ---->setupcreated ---->setupbeforeMount ---->onBeforeMountmounted ---->onMountedbeforeUpdate ---->onBeforeUpdateupdated ---->onUpdatedbeforeDestory ---->onBeforeUnmountdestoryed ---->onUnmounted
可以看到,setup 函数代替了 beforeCreate和created 两个生命周期函数,因此我们认为setup的执行时间在beforeCreate 和created 之间
为了更好的Tree-shaking,Vue3的生命周期函数都是从 vue 中导入,再进行直接调用
//从 vue 中引入 多个生命周期函数
import {onBeforeMount, onMounted, onBeforeUpdate, onUpdated,
onBeforeUnmount, unMounted} from 'vue'
export default {
name: 'App',
setup() {
onBeforeMount(() => {
// 在挂载前执行
})
onMounted(() => {
// 在挂载后执行
})
onBeforeUpdate(() => {
// 在更新前前执行
})
onUpdated(() => {
// 在更新后执行
})
onBeforeUnmount(() => {
// 在组件销毁前执行
})
unMounted(() => {
// 在组件销毁后执行
})
return {}
}
}
以上就是Vue3中生命周期函数的一点变化!