面试题答案
一键面试迁移思路
在Vue 2中,beforeDestroy
钩子在实例销毁之前调用,在此处进行解绑事件监听、清除定时器等操作。在Vue 3中,beforeDestroy
钩子被重命名为beforeUnmount
,功能基本一致,所以迁移时将相关逻辑从beforeDestroy
移动到beforeUnmount
即可。
具体代码实现步骤
- 查找
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>
- 迁移到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
钩子的迁移,实现资源释放逻辑的正确转移。