MST

星途 面试题库

面试题:Vue 生命周期钩子在 2.x 与 3.x 版本中的主要差异有哪些

请详细阐述 Vue 2.x 到 3.x 版本中,生命周期钩子函数在名称、使用方式、执行时机等方面的主要差异,并举例说明如何在迁移时处理这些变化。
35.9万 热度难度
前端开发Vue

知识考点

AI 面试

面试题答案

一键面试

名称差异

  1. Vue 2.x:常见的生命周期钩子函数有 beforeCreatecreatedbeforeMountmountedbeforeUpdateupdatedbeforeDestroydestroyed
  2. Vue 3.x:在 Vue 3.x 中,beforeDestroy 改名为 beforeUnmountdestroyed 改名为 unmounted。同时新增了 setup 函数,它在 beforeCreatecreated 之前执行,作为组件创建之前的入口。

使用方式差异

  1. Vue 2.x:通常在 Vue 组件的选项式 API 中使用,例如:
<template>
  <div></div>
</template>

<script>
export default {
  beforeCreate() {
    console.log('beforeCreate');
  },
  created() {
    console.log('created');
  }
}
</script>
  1. Vue 3.x
    • 选项式 API 基本保持一致,但在组合式 API 中使用有所不同。例如在 setup 函数中使用生命周期钩子,需要从 vue 中导入对应的函数:
<template>
  <div></div>
</template>

<script setup>
import { onBeforeMount, onMounted } from 'vue';

onBeforeMount(() => {
  console.log('beforeMount');
});

onMounted(() => {
  console.log('mounted');
});
</script>

执行时机差异

  1. Vue 2.x:生命周期钩子按照传统的组件创建、挂载、更新、销毁流程执行。
  2. Vue 3.x:整体执行时机基本不变,但 setup 函数的引入改变了组件初始化逻辑的入口。setup 函数在组件实例创建之前执行,此时 this 还未指向组件实例,而在 beforeCreatecreatedthis 已经可以访问组件实例。

迁移处理示例

假设我们有一个 Vue 2.x 组件:

<template>
  <div>{{ message }}</div>
</template>

<script>
export default {
  data() {
    return {
      message: 'Hello Vue 2'
    };
  },
  beforeDestroy() {
    console.log('Component will be destroyed');
  },
  destroyed() {
    console.log('Component has been destroyed');
  }
}
</script>

迁移到 Vue 3.x 时,使用选项式 API:

<template>
  <div>{{ message }}</div>
</template>

<script>
export default {
  data() {
    return {
      message: 'Hello Vue 3'
    };
  },
  beforeUnmount() {
    console.log('Component will be unmounted');
  },
  unmounted() {
    console.log('Component has been unmounted');
  }
}
</script>

如果使用组合式 API:

<template>
  <div>{{ message }}</div>
</template>

<script setup>
import { ref, onBeforeUnmount, onUnmounted } from 'vue';

const message = ref('Hello Vue 3');

onBeforeUnmount(() => {
  console.log('Component will be unmounted');
});

onUnmounted(() => {
  console.log('Component has been unmounted');
});
</script>

通过以上方式,根据 Vue 3.x 的新特性,对生命周期钩子函数进行改名和调整使用方式,完成从 Vue 2.x 到 3.x 的迁移。