第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. 常见应用场景
-
数据请求:
onMounted(async () => {
const data = await fetchData()
list.value = data
})
-
事件监听与清理:
onMounted(() => {
window.addEventListener('resize', handleResize)
})
onUnmounted(() => {
window.removeEventListener('resize', handleResize)
})
-
定时器管理:
let timer
onMounted(() => {
timer = setInterval(() => {
// ...
}, 1000)
})
onUnmounted(() => {
clearInterval(timer)
})
4. 注意事项
-
避免在
onUpdated
中修改状态:可能导致无限更新循环 -
SSR场景:
onBeforeMount
和onMounted
不会在服务端执行 -
组合式API特性:钩子函数需显式导入,按需使用
5. 与Options API对比
// Options API写法
export default {
mounted() { /* ... */ },
beforeUnmount() { /* ... */ }
}
// Composition API写法(更灵活的组合)
setup() {
onMounted(() => { /* ... */ })
}
最佳实践:
-
资源清理(事件/定时器)务必在
onUnmounted
中处理 -
复杂逻辑拆分到自定义Hook中(如
useFetch
) -
避免在生命周期中编写过多业务逻辑,保持职责单一