当前位置: 首页 > news >正文

Vue的生命周期

生命周期:

vue2中的生命周期:

  • 创建阶段:beforeCreate、created
  • 挂载阶段:beforeMount、mounted
  • 更新阶段:beforeUpdate、updated
  • 销毁阶段:beforeDestroy、destroyed

详细介绍:

  • beforeCreate:在实例初始化之后,数据观测 (data observer) 和事件配置 (event/watcher setup) 之前调用。此时无法访问到 data、computed 和 watch 等属性。

  • created:在实例创建完成后被立即调用。此时可以访问到 data、computed 和 watch 等属性,但还未挂载到 DOM 上。

  • beforeMount:在挂载开始之前被调用。相关的 render 函数首次被调用。

  • mounted:实例被挂载后调用,此时组件已经在 DOM 中渲染完成。可以访问到 DOM 元素。

  • beforeUpdate:数据更新时调用,发生在虚拟 DOM 重新渲染和打补丁之前。

  • updated:组件更新完成后调用,此时虚拟 DOM 已重新渲染并应用补丁。

  • beforeDestroy:实例销毁之前调用。在这一步,实例仍然完全可用。

  • destroyed:实例销毁后调用,此时所有的事件监听器被移除,所有的子实例也被销毁。

Vue3的生命周期:

  • 创建阶段:setup
  • 挂载阶段:onBeforeMount、onMounted
  • 更新阶段:onBeforeUpdate,onUpdated
  • 卸载阶段:onBeforeUnmount,onUnmounted

详细介绍:

  • setup():在 Vue 3 中,setup() 函数取代了 beforeCreate 和 created。在 setup() 函数中,可以定义响应式数据和方法,并返回需要在模板中使用的数据和方法。

  • onBeforeMount:在挂载开始之前被调用,相关的 render 函数首次被调用。

  • onMounted:实例被挂载后调用,此时组件已经在 DOM 中渲染完成。可以访问到 DOM 元素。

  • onBeforeUpdate:数据更新时调用,发生在虚拟 DOM 重新渲染和打补丁之前。

  • onUpdated:组件更新完成后调用,此时虚拟 DOM 已重新渲染并应用补丁。

  • onBeforeUnmount:在卸载组件之前调用。

  • onUnmounted:组件卸载后调用。

常用的钩子:onMounted(挂在完毕)、onUpdated(更新完毕)、onBeforeUnmounted(卸载之前)

使用的时候,需要将其导入到script标签中:

例如:

<template><div class="divBox"><h2>功德箱:{{ sum }}</h2><button @click="sum++">敲击</button></div>
</template><script setup name="lifeCycle" lang="ts">
import { onBeforeMount, ref,onMounted,onBeforeUpdate,onUpdated,onBeforeUnmount,onUnmounted} from "vue";//数据
let sum = ref(0);//方法
// function add() {
//   sum.value++;
// }//创建
console.log("创建~");//挂载前
onBeforeMount(()=>{console.log("挂载前~");
})//挂载完毕
onMounted(()=>{console.log("子---挂载完毕~");
})//更新前
onBeforeUpdate(()=>{console.log("更新前~");
})//更新完毕
onUpdated(()=>{console.log("更新完毕~");
})//卸载前
onBeforeUnmount(()=>{console.log("卸载前~");
})//卸载完毕
onUnmounted(()=>{console.log("卸载完毕~");
})</script><style scoped>
@import "/src/Css/divBox.css";
</style>


http://www.mrgr.cn/news/50949.html

相关文章:

  • LeetCode146. LRU 缓存(2024秋季每日一题 37)
  • NVIC和EXIT寄存器工作
  • MediaGo:革新视频下载体验的开源神器
  • 深入解析CSS中的!important规则
  • C++ 的特性可以不用在主函数中调用
  • 【AI学习】Mamba学习(六):HiPPO论文中的离散化SSM的矩阵近似计算
  • OpenCV-人脸检测
  • 从零开始的LeetCode刷题日记:102.二叉树的层序遍历
  • RHCE第一天
  • C语言[经典题——4×5矩形阵]
  • Servlet的HttpServletRequest
  • [结构体]谁考了第k名
  • k8s 1.28 集群部署
  • 自定义类型:结构体【上】
  • error: cannot find symbol import android.os.SystemProperties;
  • 阐述懒加载?
  • 嵌入式硬件设计
  • shell命令笔记记录
  • 贪吃蛇游戏(代码篇)
  • fork中的死锁问题