• Vue中的组件生命周期


    一个组件从创建到销毁的过程 成为生命周期。
    在我们使用Vue3 组合式API 是没有 beforeCreate 和 created 这两个生命周期的

    组件生命周期如下:

    在这里插入图片描述

    • onBeforeMount() 在组件DOM实际渲染安装之前调用。在这一步中,根元素还不存在。
    • onMounted() 在组件的第一次渲染后调用,该元素现在可用,允许直接DOM访问
    • onBeforeUpdate() 数据更新时调用,发生在虚拟 DOM 打补丁之前。
    • onUpdated() DOM更新后,updated的方法即会调用。
    • onBeforeUnmount() 在卸载组件实例之前调用。在这个阶段,实例仍然是完全正常的。
    • onUnmounted() 卸载组件实例后调用。调用此钩子时,组件实例的所有指令都被解除绑定,所有事件侦听器都被移除,所有子组件实例被卸载。
    选项API 和组合式API钩子对比
    选项式API组合式API
    beforeCreateNot needed*
    createdNot needed*
    beforeMountonBeforeMount
    mountedonMounted
    beforeUpdateonBeforeUpdate
    updatedonUpdated
    beforeUnmountonBeforeUnmount
    unmountedonUnmounted
    errorCapturedonErrorCaptured
    renderTrackedonRenderTracked
    renderTriggeredonRenderTriggered
    activatedonActivated
    deactivatedonDeactivated

    代码示例:

    <template>
       <h3>我是组件h3>
       <div ref="div">{{str}}div>
       <button @click="change">修改strbutton>
    template>
    <script setup lang="ts">
    import { ref,onBeforeMount,onMounted,onBeforeUpdate,onUpdated,onBeforeUnmount,onUnmounted } from 'vue';
    const str=ref<string>('我是大漂亮');
    console.log(str);
    const div=ref<HTMLDivElement>();
    const change=()=>{
       str.value='小可爱';
    }
    onBeforeMount(()=>{
       console.log('创建前',div.value);
    })
    onMounted(()=>{
       console.log('挂载完成',div.value);
    })
    onBeforeUpdate(()=>{
       console.log('更新前')
    })
    onUpdated(()=>{
       console.log('更新完成')
    })
    onBeforeUnmount(()=>{
       console.log('卸载之前')
    })
    onUnmounted(()=>{
       console.log('卸载完成')
    })
    script>
    <style scoped>
    style>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34

    页面加载完成:
    Ref<“我是大漂亮”>
    创建前 undefined
    挂载完成

    <div>小可爱div>"
    
    • 1
    点击button后:

    控制台打印:
    更新前
    更新完成

  • 相关阅读:
    python操作sqlite报错:sqlite3.OperationalError: unrecognized token: “630008.OF“
    整形和浮点型是如何在内存中的存储
    四肽Suc-AAPD-对硝基苯胺,165174-58-3
    c语言实现内存池
    Android 消息机制
    MySQL添加外键约束经典案例
    Web3中文|区块链游戏的成长之痛
    索引三星结构
    C语言-入门-语法-指针(十二)
    17.2 实现无管道正向CMD
  • 原文地址:https://blog.csdn.net/weixin_42491648/article/details/128088401