vue生命周期函数变化

114 阅读1分钟

迁移

在 Vue 2 中,我们可以通过事件来监听组件生命周期中的关键阶段。这些事件名都是以 hook: 前缀开头,并跟随相应的生命周期钩子的名字。

在 Vue 3 中,这个前缀已被更改为 vue:。额外地,这些事件现在也可用于 HTML 元素,和在组件上的用法一样。

vue2

<template>
  <ChildComponent @hook:mounted="onVnodeMounted" @hook:beforeMount="onBeforeMount" />
</template>

<script>
export default {
  components: {
    ChildComponent: () => import('@/components/ChildComponent.vue')
  },
  data() {
    return {};
  },
  methods: {
    onMounted() {
      console.log('====== ChildComponent mounted');
    },
    onBeforeMount() {
      console.log('====== ChildComponent beforeMount');
    }
  }
};
</script>

vue3:

当前测试vue@3.2.33, 以下的两种当时都可以。

<template>
 <ChildComponent @vnodeMounted="onVnodeMounted" @vue:beforeMount="onBeforeMount" />
</template>

<script setup>
const ChildComponent = defineAsyncComponent(() => import('@/components/ChildComponent.vue'));

const onMounted = () => {
 console.log('====== ChildComponent mounted');
};

const onBeforeMount = () => {
 console.log('====== ChildComponent beforeMount');
};
</script>

参考

VNode 生命周期事件