生命周期
钩子与错误处理。
生命周期
这一课你将能做到
- 说出 Vue 组件从创建到销毁的完整生命周期
- 用
onMounted在组件挂载后执行初始化操作 - 用
onUnmounted清理定时器、事件监听等副作用 - 用
onUpdated在组件更新后执行操作
为什么要学
组件不是「一直活着」的。它有出生(创建)、成长(更新)、死亡(销毁)的过程。很多操作必须在特定阶段执行:比如组件挂载后才能操作 DOM,组件销毁前必须清理定时器,否则内存泄漏。
人话:生命周期就像人的「人生阶段」。出生时要做登记(初始化数据),成年时要工作(更新视图),去世前要立遗嘱(清理资源)。错过阶段就出问题。
先建立图像
创建阶段 挂载阶段 更新阶段 销毁阶段
│ │ │ │
setup() ──→ onBeforeMount ──→ onMounted ──→ onBeforeUpdate ──→ onUpdated ──→ onBeforeUnmount ──→ onUnmounted
(即将挂载) (已挂载) (即将更新) (已更新) (即将卸载) (已卸载)
跟着做
步骤 1:onMounted 挂载后执行
<script setup>
import { ref, onMounted } from 'vue'
const chartRef = ref(null)
onMounted(() => {
// 此时 DOM 已渲染,可以操作
console.log(chartRef.value) // <div> 元素
// 初始化图表、发请求、绑定事件
})
</script>
<template>
<div ref="chartRef">图表容器</div>
</template>
步骤 2:onUnmounted 销毁前清理
<script setup>
import { onMounted, onUnmounted } from 'vue'
let timer = null
onMounted(() => {
timer = setInterval(() => console.log('tick'), 1000)
})
onUnmounted(() => {
clearInterval(timer) // 必须清理,否则内存泄漏
})
</script>
步骤 3:onUpdated 更新后执行
<script setup>
import { ref, onUpdated } from 'vue'
const list = ref([])
onUpdated(() => {
// DOM 更新后执行,比如滚动到底部
const el = document.querySelector('.list')
el.scrollTop = el.scrollHeight
})
</script>
步骤 4:常用钩子速查
<script setup>
import { onBeforeMount, onMounted, onBeforeUpdate, onUpdated, onBeforeUnmount, onUnmounted } from 'vue'
onBeforeMount(() => console.log('即将挂载'))
onMounted(() => console.log('已挂载'))
onBeforeUpdate(() => console.log('即将更新'))
onUpdated(() => console.log('已更新'))
onBeforeUnmount(() => console.log('即将卸载'))
onUnmounted(() => console.log('已卸载'))
</script>
步骤 5:实际场景——请求数据 + 清理
<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
const data = ref(null)
let abortController = null
onMounted(async () => {
abortController = new AbortController()
try {
const res = await fetch('/api/data', { signal: abortController.signal })
data.value = await res.json()
} catch (e) {
if (e.name !== 'AbortError') throw e
}
})
onUnmounted(() => {
abortController?.abort() // 组件销毁时取消请求
})
</script>