一、Vue2的生命周期
生命嘛,总是和人类比。从出生到死亡的整个过程。
vue2的生命周期是分为4个阶段8个函数
具体如下:
生命周期 | 函数 |
---|---|
创建 | beforeCreate(), created() |
挂载 | beforeMount(), mounted() |
更新 | beforeUpdate(), updated() |
销毁 | beforeDestroy(),destroyed() |
二、Vue3的生命周期
vue2的生命周期是分为4个阶段7个函数
具体如下:
生命周期 | 函数 |
---|---|
创建 | setup |
挂载 | onBeforeMount(), onMounted() |
更新 | onBeforeUpdate(), onUpdated() |
销毁 | onBeforeUnmount(),onUnmounted() |
对比vue2基本是一样的,创建合并到了一起
通过代码查看下效果:
<template>
<div class="person">
<h3>姓名:{{ person.name }}</h3>
<h3>年龄:{{ person.age }}</h3>
<button @click="updatePersonAge">修改age</button>
</div>
</template>
<script lang='ts' setup name="Vue3life">
import { onBeforeMount, onBeforeUnmount, onBeforeUpdate, onMounted, onUnmounted, onUpdated, ref } from 'vue'
let person = ref(
{
name: "李四",
age: 99
}
)
function updatePersonAge() {
person.value.age += 1
}
console.log('创建');
onBeforeMount(() => {
console.log('挂載前')
})
// 挂载完毕
onMounted(() => {
console.log('挂载完毕')
})
// 更新前
onBeforeUpdate(() => {
console.log('更新前')
})
// 更新完毕
onUpdated(() => {
console.log('更新完毕')
})
// 卸载前
onBeforeUnmount(() => {
console.log('卸载前')
})
// 卸载前
onUnmounted(() => {
console.log('卸载完成');
})
</script>