Vue3生命周期

时间:2025-01-20 13:28:39

Vue3生命周期相对于Vue2生命周期来说,区别不是很大,最大的区别在Vue2的beforeCreate和Created用在Vue3中用setup代替,其他的生命周期只是在命名上有改变。

beforeDestroy 改名为 beforeUnmount
destroyed 改名为 unmounted
beforeCreate => setup
created => setup
beforeMount => onBeforeMount
mounted => onMounted
beforeUpdate => onBeforeUpdate
updated => onUpdated
beforeUnmount => onBeforeUnmount
unmounted => onUnmounted

特别注意的是:Vue3所有的生命周期需要写到setup中,如下:

setup() {
    onMounted(() => {
      console.log('mounted')
    })
    onUnmounted(() => {
      console.log('onUnmounted')
    })   
}