2022-05-05 20:40

Vue3.0的新特性(二) — 生命周期函数

王姐姐

WEB前端

(672)

(0)

收藏

我们都知道,在Vue2.x中有8个生命周期函数:

  • beforeCreate

  • created

  • beforeMount

  • mounted

  • beforeUpdate

  • updated

  • beforeDestroy

  • destroyed

在vue3中,新增了一个setup生命周期函数,setup执行的时机是在beforeCreate生命函数之前执行,因此在这个函数中是不能通过this来获取实例的;同时为了命名的统一,将beforeDestroy改名为beforeUnmountdestroyed改名为unmounted,因此vue3有以下生命周期函数:

  • beforeCreate(建议使用setup代替)

  • created(建议使用setup代替)

  • setup

  • beforeMount

  • mounted

  • beforeUpdate

  • updated

  • beforeUnmount

  • unmounted

同时,vue3新增了生命周期钩子,我们可以通过在生命周期函数前加on来访问组件的生命周期,我们可以使用以下生命周期钩子:

  • onBeforeMount

  • onMounted

  • onBeforeUpdate

  • onUpdated

  • onBeforeUnmount

  • onUnmounted

  • onErrorCaptured

  • onRenderTracked

  • onRenderTriggered

那么这些钩子函数如何来进行调用呢?我们在setup中挂载生命周期钩子,当执行到对应的生命周期时,就调用对应的钩子函数:

import { onBeforeMount, onMounted } from "vue";
export default {
  setup() {
    console.log("----setup----");
    onBeforeMount(() => {
      // beforeMount代码执行    });
    onMounted(() => {
      // mounted代码执行    });
  },}


0条评论

点击登录参与评论