概念: Vue组件实例在创建时要经历一系列的初始化步骤, 在此过程中Vue会在合适的时机, 调用特定的函数, 从而让开发者有机会在特定阶段运行自己的代码, 这些特定的函数统称为: 生命周期钩子
规律: 生命周期整体分为四个阶段, 分别是: 创建、挂载、更新、卸载, 每个阶段都有两个钩子, 一前一后.
Vue2的生命周期:
创建阶段: beforeCreate、created
挂载阶段: beforeMount、mounted
更新阶段: beforeUpdate、updated
销毁阶段: beforeDestroy、destroyed
Vue3的生命周期:
创建阶段: setup
挂载阶段: onBeforeMount、onMount
更新阶段: onBeforeUpdate、onUpdate
卸载阶段: onBeforeUnmount、onUnmounted
常用的钩子: onMount(挂载完毕)、onUpdate(更新完毕)、onBeforeUnmount(卸载之前)
<template>
<div class="person">
<h2>当前求和为:{{ sum }}</h2>
<button @click="changeSum">点我sum+1</button>
</div>
</template>
<!-- vue3写法 -->
<script lang="ts" setup name="Person">
import {
ref,
onBeforeMount,
onMounted,
onBeforeUpdate,
onUpdated,
onBeforeUnmount,
onUnmounted
} from 'vue'
// 数据
let sum = ref(0)
// 方法
function changeSum() {
sum.value += 1
}
console.log('setup')
// 生命周期钩子
onBeforeMount(()=>{
console.log('挂载之前')
})
onMounted(()=>{
console.log('挂载完毕')
})
onBeforeUpdate(()=>{
console.log('更新之前')
})
onUpdated(()=>{
console.log('更新完毕')
})
onBeforeUnmount(()=>{
console.log('卸载之前')
})
onUnmounted(()=>{
console.log('卸载完毕')
})
</script>

