<template>
<div class="app">
<h1>{{ msg }}</h1>
<h2 ref="h2Ref">{{ num }}</h2>
<el-button @click="add()">+1</el-button>
<el-button @click="destroy()">销毁</el-button>
</div>
</template>
<script setup>
import { ref, onMounted, onBeforeMount, onUpdated, onBeforeUpdate, onUnmounted, onBeforeUnmount } from 'vue'
const msg = 'Vue的生命周期'
const num = ref(1)
const add = () => {
num.value++
}
const h2Ref = ref()
console.log(h2Ref);
// 这个代码在组件显示之前,也就是挂载之前就执行了,这时候的h2还没有被加载,使用我们拿到的输出结果会是null
const h2_ = document.querySelector('h2')
console.log(h2_);//null
// 创建
// 创建前
// 创建后
// 挂载
// 这两个都会在网页显示内容之前执行
// 挂载前
onBeforeMount(() => {
alert('挂载前')
})
// 挂载后
onMounted(() => {
alert('挂载后')
// 这个代码在组件挂载之后执行,能正常拿到h2
const h2 = document.querySelector('h2')
console.log(h2);//<h2>1<h2>
})
// 更新
// 这两个函数是在界面上组件已经显示了,你点击或者其他触发方式使组件样式发送变化后进行执行
// 更新前
onBeforeUpdate(() => {
alert('更新前')
})
// 更新后
onUpdated(() => {
alert('更新后')
})
const destroy = () => {
h2Ref.value = null
}
// 销毁
// 销毁前
onBeforeUnmount(() => {
alert('卸载前')
})
// 销毁后
onUnmounted(() => {
alert('卸载后')
})
</script>
生命周期函数
最新推荐文章于 2024-07-25 14:02:05 发布