Vue3 生命周期有哪些变化?与 Vue2 有什么区别?
生命周期变化
- 选项式API改名为组合式API命名方式
beforeCreate
和created
被setup
替代- 其他生命周期添加
on
前缀:beforeMount
→onBeforeMount
mounted
→onMounted
beforeUpdate
→onBeforeUpdate
updated
→onUpdated
beforeUnmount
→onBeforeUnmount
unmounted
→onUnmounted
新增特性
- 新增
onServerPrefetch
用于服务端渲染 - 支持在
setup
中使用多个相同生命周期import { onMounted } from 'vue'
setup() {
onMounted(() => {
console.log('第一次挂载')
})
onMounted(() => {
console.log('第二次挂载')
})
}
与 Vue2 主要区别
Vue2 | Vue3 | 变化说明 |
---|---|---|
beforeCreate | setup() | 组合式API入口 |
created | setup() | 组合式API入口 |
beforeMount | onBeforeMount | 添加on前缀 |
mounted | onMounted | 添加on前缀 |
beforeDestroy | onBeforeUnmount | 更准确的命名 |
destroyed | onUnmounted | 更准确的命名 |
使用注意事项
- 在
setup
中同步使用生命周期钩子 - 卸载阶段钩子需要清理副作用
- 服务端渲染使用
onServerPrefetch
- 组合式API支持更灵活的逻辑复用
评论