<template>
<div id='home'>dom创建前后</div>
<div>mount更新前后{{count}}</div>
<n-button @click="count++">改变count</n-button>
<div v-if="flag">卸载DOM</div>
<n-button @click="flag=!flag">改变组件状态</n-button>
</template>
<script setup lang="ts">
import { onBeforeMount, onMounted , onBeforeUpdate, ref, Ref, onUpdated, onBeforeUnmount, onUnmounted } from 'vue';
import { NButton } from 'naive-ui';
const count =ref(0)
const flag=ref(true)
//onBeforeMount生命周期挂钩:DOM创建之前
onBeforeMount( () => {
let div=document.querySelector('#home')
console.log('DOM创建之前onBeforeMount',div)
})
//onMounted生命周期挂钩:数据初始化侯,DOM创建完成,所以操作DOM的时候,可以直接写在onMounted里面
onMounted(async () => {
let div=document.querySelector('#home')
console.log('DOM创建完成onMounted',div)
const data = await mockRequest.get('/huchen')
console.log(data)
})
//onBeforeUpdate生命周期挂钩:更新DOM前
onBeforeUpdate( () => {
console.log('DOM更新前onBeforeUpdate');
})
//onUpdated生命周期挂钩:更新DOM完成
onUpdated( () => {
console.log('DOM更新完成onUpdated');
})
//onBeforeUnmount生命周期挂钩:卸载DOM前
onBeforeUnmount(()=>{
console.log('卸载DOM前onBeforeUnmount');
})
//onUnmounted生命周期挂钩:卸载DOM完成
onUnmounted(()=>{
console.log('卸载DOM完成onUnmounted');
})
12-03
1172
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
11-28
1366
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)