生命周期变化

  1. 选项式API改名为组合式API命名方式
  2. beforeCreatecreatedsetup替代
  3. 其他生命周期添加on前缀:
    • beforeMountonBeforeMount
    • mountedonMounted
    • beforeUpdateonBeforeUpdate
    • updatedonUpdated
    • beforeUnmountonBeforeUnmount
    • unmountedonUnmounted

新增特性

  1. 新增onServerPrefetch用于服务端渲染
  2. 支持在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 更准确的命名

使用注意事项

  1. setup中同步使用生命周期钩子
  2. 卸载阶段钩子需要清理副作用
  3. 服务端渲染使用onServerPrefetch
  4. 组合式API支持更灵活的逻辑复用