Vue3 的生命周期钩子有哪些?和 Vue2 有什么变化?
Vue3 生命周期(Composition API)
import {
onBeforeMount,
onMounted,
onBeforeUpdate,
onUpdated,
onBeforeUnmount,
onUnmounted,
onErrorCaptured,
onActivated,
onDeactivated
} from 'vue'
完整流程
挂载阶段:
setup() → onBeforeMount → DOM 挂载 → onMounted
更新阶段:
数据变化 → onBeforeUpdate → DOM 更新 → onUpdated
卸载阶段:
onBeforeUnmount → onUnmounted
KeepAlive:
onActivated(激活)/ onDeactivated(停用)
错误处理:
onErrorCaptured
Vue2 vs Vue3 对比
| Vue2 |
Vue3 (Composition API) |
说明 |
| beforeCreate |
setup() |
已被 setup 取代 |
| created |
setup() |
已被 setup 取代 |
| beforeMount |
onBeforeMount |
挂载前 |
| mounted |
onMounted |
挂载后 |
| beforeUpdate |
onBeforeUpdate |
更新前 |
| updated |
onUpdated |
更新后 |
| beforeDestroy |
onBeforeUnmount |
卸载前(改名) |
| destroyed |
onUnmounted |
卸载后(改名) |
| activated |
onActivated |
KeepAlive 激活 |
| deactivated |
onDeactivated |
KeepAlive 停用 |
| errorCaptured |
onErrorCaptured |
错误捕获 |
使用示例
import { ref, onMounted, onUnmounted } from 'vue'
export function useMousePosition() {
const x = ref(0)
const y = ref(0)
const update = (e) => {
x.value = e.pageX
y.value = e.pageY
}
onMounted(() => {
window.addEventListener('mousemove', update)
})
onUnmounted(() => {
window.removeEventListener('mousemove', update)
})
return { x, y }
}
关键变化
beforeCreate / created → 直接在 setup() 中编写
destroy 相关改名为 unmount(语义更准确)
- 生命周期函数在
setup 中同步调用
- 可以在同一组件中多次调用同一钩子:
onMounted(() => console.log('first'))
onMounted(() => console.log('second'))
新增钩子
onServerPrefetch:SSR 专用,服务端预取数据
onRenderTracked:调试用,渲染时追踪依赖(开发模式)
onRenderTriggered:调试用,触发渲染时调用(开发模式)
同分类其他题目