MST

星途 面试题库

面试题:Vue 3中如何将Vue 2基于beforeDestroy钩子的业务逻辑迁移

假设在Vue 2项目中有一段在beforeDestroy钩子内用于解绑事件监听、清除定时器等资源释放的业务逻辑,在迁移到Vue 3时,应该如何利用新的生命周期钩子进行改造?请详细说明迁移思路和具体代码实现步骤。
40.2万 热度难度
前端开发Vue

知识考点

AI 面试

面试题答案

一键面试

迁移思路

在Vue 2中,beforeDestroy钩子在实例销毁之前调用,在此处进行解绑事件监听、清除定时器等操作。在Vue 3中,beforeDestroy钩子被重命名为beforeUnmount,功能基本一致,所以迁移时将相关逻辑从beforeDestroy移动到beforeUnmount即可。

具体代码实现步骤

  1. 查找beforeDestroy钩子:在Vue 2项目中,定位到包含beforeDestroy钩子的组件。例如:
<template>
  <div>
    <!-- 组件内容 -->
  </div>
</template>

<script>
export default {
  data() {
    return {
      timer: null
    };
  },
  mounted() {
    this.timer = setInterval(() => {
      console.log('定时器运行中');
    }, 1000);
  },
  beforeDestroy() {
    clearInterval(this.timer);
    console.log('Vue 2中清除定时器');
  }
};
</script>
  1. 迁移到Vue 3的beforeUnmount钩子:将beforeDestroy钩子中的逻辑迁移到Vue 3组件的beforeUnmount钩子中。Vue 3有两种写法,选项式API和组合式API。
    • 选项式API
<template>
  <div>
    <!-- 组件内容 -->
  </div>
</template>

<script setup>
import { onBeforeUnmount } from 'vue';
export default {
  data() {
    return {
      timer: null
    };
  },
  mounted() {
    this.timer = setInterval(() => {
      console.log('定时器运行中');
    }, 1000);
  },
  beforeUnmount() {
    clearInterval(this.timer);
    console.log('Vue 3选项式API中清除定时器');
  }
};
</script>
- **组合式API**:
<template>
  <div>
    <!-- 组件内容 -->
  </div>
</template>

<script setup>
import { onBeforeUnmount, ref } from 'vue';
const timer = ref(null);
onMounted(() => {
  timer.value = setInterval(() => {
    console.log('定时器运行中');
  }, 1000);
});
onBeforeUnmount(() => {
  clearInterval(timer.value);
  console.log('Vue 3组合式API中清除定时器');
});
</script>

通过以上步骤,即可完成从Vue 2的beforeDestroy钩子到Vue 3的beforeUnmount钩子的迁移,实现资源释放逻辑的正确转移。