Vue3生命周期

Vue3.0中可以继续使用Vue2.x中的生命周期钩子,但有有两个被更名:

  • beforeDestroy改名为 beforeUnmount
  • destroyed改名为 unmounted

Vue3.0也提供了 Composition API 形式的生命周期钩子,与Vue2.x中钩子对应关系如下:

    • beforeCreate===>setup()
    • created=======>setup()
    • beforeMount ===>onBeforeMount
    • mounted=======>onMounted
    • beforeUpdate===>onBeforeUpdate
    • updated =======>onUpdated
    • beforeUnmount ==>onBeforeUnmount
    • unmounted =====>onUnmounted
复制代码
<template>
    <h2>当前求和为:{{sum}}</h2>
    <button @click="sum++">点我+1</button>
</template>

<script>
    import {ref,onBeforeMount,onMounted,onBeforeUpdate,onUpdated,onBeforeUnmount,onUnmounted} from 'vue'
    export default {
        name: 'Demo',
        
        setup(){
            console.log('---setup---')
            //数据
            let sum = ref(0)

            //通过组合式API的形式去使用生命周期钩子
            onBeforeMount(()=>{
                console.log('---onBeforeMount---')
            })
            onMounted(()=>{
                console.log('---onMounted---')
            })
            onBeforeUpdate(()=>{
                console.log('---onBeforeUpdate---')
            })
            onUpdated(()=>{
                console.log('---onUpdated---')
            })
            onBeforeUnmount(()=>{
                console.log('---onBeforeUnmount---')
            })
            onUnmounted(()=>{
                console.log('---onUnmounted---')
            })

            //返回一个对象(常用)
            return {sum}
        },
        //通过配置项的形式使用生命周期钩子
        //#region 
        beforeCreate() {
            console.log('---beforeCreate---')
        },
        created() {
            console.log('---created---')
        },
        beforeMount() {
            console.log('---beforeMount---')
        },
        mounted() {
            console.log('---mounted---')
        },
        beforeUpdate(){
            console.log('---beforeUpdate---')
        },
        updated() {
            console.log('---updated---')
        },
        beforeUnmount() {
            console.log('---beforeUnmount---')
        },
        unmounted() {
            console.log('---unmounted---')
        },
        //#endregion
    }
</script>
复制代码

 

  

posted @   安静点--  阅读(169)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
点击右上角即可分享
微信分享提示