vue3 生命周期与vue2的区别

vue3生命周期

img

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

    • beforeDestroy改名为 beforeUnmount
    • destroyed改名为 unmounted
  • Vue3.0也提供了 Composition API 形式的生命周期钩子,与Vue2.x中钩子对应关系如下:

    • beforeCreate===>setup()
    • created=======>setup()
    • beforeCreatecreated没有对应组合式API,setup()相当于beforeCreatecreated,对于配置项setup()的执行时机早于配置项beforeCreatecreated
    • beforeMount ===>onBeforeMount
    • mounted=======>onMounted
    • beforeUpdate===>onBeforeUpdate
    • updated =======>onUpdated
    • beforeUnmount ==>onBeforeUnmount
    • unmounted =====>onUnmounted
    • 如果组合式API的生命周期与配置项形式的生命周期一起写,组合式API的生命周期的执行时机优先于配置项形式的生命周期。
    • 一般情况下统一使用组合式API的生命周期,或者统一使用配置项形式的生命周期
<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}
    },
      
    //通过配置项的形式使用生命周期钩子
    /*
    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---')
    },
    */
  }
</script>

img

img

  • 10
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值