Vue3 组合式api 的生命周期
- beforeCreate created,setup语法糖模式(组合式api)是没有这两个生命周期的,用setup去代替
- onBeforeMount 获取不到DOM, onMounted可以获取DOM
- onBeforeUpdate获取的是更新之前的DOM,onUpdated获取的是更新之后的DOM
- onActivated和onDeactivated是keep-alive独有的组件,在这里不描述
<template>
<div>演示生命周期</div>
<div ref="div">{{str}}</div>
<button @click="change">修改</button>
</template>
<script setup lang='ts'>
import { ref, onBeforeMount, onMounted, onBeforeUpdate, onUpdated, onBeforeUnmount, onUnmounted, onRenderTracked, onRenderTriggered } from 'vue';
const str = ref<string>('aaa')
const div = ref<HTMLDivElement>()
const change = () => {
str.value = '我被改变了'
}
// 创建
onBeforeMount(() => {
console.log('创建之前', div.value);
})
onMounted(() => {
console.log('创建完成', div.value);
})
// 更新
onBeforeUpdate(() => {
console.log('更新组件之前', div.value?.innerText);
})
onUpdated(() => {
console.log('更新组件完成', div.value?.innerText);
})
// 卸载
onBeforeUnmount(() => {
console.log('销毁之前');
})
onUnmounted(() => {
console.log('销毁完成');
})
// 调试
onRenderTracked((e) => {
console.log(e);
})
onRenderTriggered((e) => {
console.log(e);
})
</script>
标签:组合式,生命周期,console,log,DOM,value,api,Vue3,div
From: https://www.cnblogs.com/wanglei1900/p/16755576.html