生命周期函数

<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>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值