beforeCreate
,created
在setup 语法糖模式下是没有这两个生命周期的
App.vue
<template><h1>Hello World</h1><!-- 通过v-if控制组件创建和销毁的生命钩子 --><A v-if="flag"></A><button @click="flag = !flag">创建和销毁</button>
</template><script setup lang="ts">
import { ref, reactive } from 'vue';
import A from './components/A.vue'
const flag = ref<Boolean>(true)
</script><style lang="scss" scoped></style>
A.vue
<template><div>i am component</div><div ref="div">{{ str }}</div><button @click="change">change</button>
</template><script setup lang="ts">
import { ref, onBeforeMount, onMounted, onUpdated, onBeforeUpdate, onUnmounted, onBeforeUnmount, onRenderTracked, onRenderTriggered } from 'vue'
console.log('setup');
const str = ref<string>('hello')
const div = ref<HTMLDivElement>()
const change = () =>{str.value = '我被改了'
}
//创建
onBeforeMount(() => {console.log('创建之前',div.value);//此时没有渲染DOM
})
onMounted(() => {console.log('创建完成',div.value);//此时有渲染DOM
})
//更新的钩子
onBeforeUpdate(() => {console.log('更新之前',div.value?.innerText);//更新之前DOM不变
})
onUpdated(() => {console.log('更新完成',div.value?.innerText);//更新之后DOM变化
})
//销毁
onBeforeUnmount(() => {console.log('销毁之前');})
onUnmounted(() => {console.log('销毁完成');})
onRenderTracked((e) => {console.log(e);//调试get(获取)
})
onRenderTriggered((e) => {console.log(e);//调试set(更改)
})
</script><style lang="scss" scoped></style>