分类
默认

Vue3 和 Vue2 的生命周期有什么区别

Options API 生命周期

  • beforeDestroy 改为 beforeUnmount
  • destroyed 改为 unmouted
  • 其他沿用 Vue2 的生命周期

例如:

beforeCreate() {
     console.log('beforeCreate')
 },
 created() {
     console.log('created')
 },
 beforeMount() {
     console.log('beforeMount')
 },
 mounted() {
     console.log('mounted')
 },
 beforeUpdate() {
     console.log('beforeUpdate')
 },
 updated() {
     console.log('updated')
 },
 // beforeDestroy 改名
 beforeUnmount() {
     console.log('beforeUnmount')
 },
 // destroyed 改名
 unmounted() {
     console.log('unmounted')
 }

打印结果:

beforeCreate
created
beforeMount
mounted
beforeUpdate
updated
beforeUnmount
unmounted

Composition API 生命周期

比如

import { onBeforeMount, onMounted, onBeforeUpdate, onUpdated, onBeforeUnmount, onUnmounted } from 'vue'
export default {
    // 等于 beforeCreate 和 created
    setup() {
        console.log('setup')

        onBeforeMount(() => {
            console.log('onBeforeMount')
        })
        onMounted(() => {
            console.log('onMounted')
        })
        onBeforeUpdate(() => {
            console.log('onBeforeUpdate')
        })
        onUpdated(() => {
            console.log('onUpdated')
        })
        onBeforeUnmount(() => {
            console.log('onBeforeUnmount')
        })
        onUnmounted(() => {
            console.log('onUnmounted')
        })

    },
}

打印结果:

setup
onBeforeMount
onMounted
onBeforeUpdate
onUpdated
onBeforeUnmount
onUnmounted