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

第10篇:组件生命周期与钩子函数

目标:理解组件生命周期的关键阶段及常用钩子


1. 生命周期图示

复制

创建阶段:setup → onBeforeMount → onMounted  
更新阶段:onBeforeUpdate → onUpdated  
卸载阶段:onBeforeUnmount → onUnmounted  
其他:onActivated(keep-alive激活)、onDeactivated(keep-alive失活)  

2. 常用钩子函数
<script setup>  
import {  
  onBeforeMount,  
  onMounted,  
  onBeforeUpdate,  
  onUpdated,  
  onBeforeUnmount,  
  onUnmounted  
} from 'vue'  

// 组件挂载前  
onBeforeMount(() => {  
  console.log('DOM挂载前')  
})  

// 组件挂载完成  
onMounted(() => {  
  console.log('DOM已挂载')  
  // 可安全访问DOM  
  const el = document.querySelector('#app')  
})  

// 数据更新前  
onBeforeUpdate(() => {  
  console.log('数据即将更新')  
})  

// 数据更新完成  
onUpdated(() => {  
  console.log('数据已更新')  
})  

// 组件卸载前  
onBeforeUnmount(() => {  
  console.log('组件即将销毁')  
})  

// 组件卸载完成  
onUnmounted(() => {  
  console.log('组件已销毁')  
})  
</script>  

3. 常见应用场景
  1. 数据请求

onMounted(async () => {  
  const data = await fetchData()  
  list.value = data  
})  
 
  1. 事件监听与清理

onMounted(() => {  
  window.addEventListener('resize', handleResize)  
})  

onUnmounted(() => {  
  window.removeEventListener('resize', handleResize)  
})  
  1. 定时器管理

let timer  
onMounted(() => {  
  timer = setInterval(() => {  
    // ...  
  }, 1000)  
})  

onUnmounted(() => {  
  clearInterval(timer)  
})  
 

4. 注意事项
  • 避免在onUpdated中修改状态:可能导致无限更新循环

  • SSR场景onBeforeMountonMounted不会在服务端执行

  • 组合式API特性:钩子函数需显式导入,按需使用


5. 与Options API对比
// Options API写法  
export default {  
  mounted() { /* ... */ },  
  beforeUnmount() { /* ... */ }  
}  

// Composition API写法(更灵活的组合)  
setup() {  
  onMounted(() => { /* ... */ })  
}  
 

最佳实践

  • 资源清理(事件/定时器)务必在onUnmounted中处理

  • 复杂逻辑拆分到自定义Hook中(如useFetch

  • 避免在生命周期中编写过多业务逻辑,保持职责单一


http://www.kler.cn/a/559527.html

相关文章:

  • 15-最后一个单词的长度
  • 全面汇总windows进程通信(三)
  • Transformer Decoder 详解
  • ThinkPHP(TP)如何做安全加固,防webshell、防篡改、防劫持、TP漏洞防护
  • 【Gin-Web】Bluebell社区项目梳理4:帖子相关接口开发及实现
  • Unity 中导入的VRM模型渲染为VRoid风格
  • 【每日八股】Redis篇(二):数据结构
  • Deepin(Linux)安装MySQL指南
  • Nginx学习笔记:常用命令端口占用报错解决Nginx核心配置文件解读
  • <02.23>Leetcode100
  • Linux-Ansible自动化运维
  • 用 PyMuPDF 和 Pillow 打造 PDF 超级工具
  • mysql实时同步到es
  • CSS通过webkit-scrollbar设置滚动条样式
  • 10. 九转金丹炼矩阵 - 矩阵置零(标记优化)
  • DeepSeek等LLM对网络安全行业的影响
  • 欢乐力扣:同构字符串
  • 使用Python和正则表达式爬取网页中的URL数据
  • WSL2下ubuntu开启NFS服务
  • STM32MP157A单片机移植Linux驱动