Vue3中生命周期函数的变化

我们知道,在每个组件在被创建时,要经过一系列的初始化过程,比如,需要设置数据监听、编译模板、实例挂载并在数据变化时触发DOM更新等。

Vue2中提供了生命周期钩子函数,如beforeCreatecreatedbeforeMountmountedbeforeUpdateupdatedbeforeDestorydestoryed等,用于在组件不同阶段执行一些我们想要的执行的操作

到了Vue3,有所变化

  1. beforeCreate ---->setup
  2. created ---->setup
  3. beforeMount ---->onBeforeMount
  4. mounted ---->onMounted
  5. beforeUpdate ---->onBeforeUpdate
  6. updated ---->onUpdated
  7. beforeDestory ---->onBeforeUnmount
  8. destoryed ---->onUnmounted

可以看到,setup 函数代替了 beforeCreatecreated 两个生命周期函数,因此我们认为setup的执行时间在beforeCreatecreated 之间

为了更好的Tree-shakingVue3的生命周期函数都是从 vue 中导入,再进行直接调用

//从 vue 中引入 多个生命周期函数
import {onBeforeMount, onMounted, onBeforeUpdate, onUpdated, 
  onBeforeUnmount, unMounted} from 'vue'
export default {
  name: 'App',
  setup() {
    onBeforeMount(() => {
      // 在挂载前执行
    })
    onMounted(() => {
      // 在挂载后执行
    })
    onBeforeUpdate(() => {
      // 在更新前前执行
    })
    onUpdated(() => {
      // 在更新后执行
    })
    onBeforeUnmount(() => {
      // 在组件销毁前执行
    })
    unMounted(() => {
      // 在组件销毁后执行
    })
    return {}
  }
  
}

以上就是Vue3中生命周期函数的一点变化!

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容