MST

星途 面试题库

面试题:Vue中beforeDestroy钩子与destroyed钩子的清理工作场景差异

请阐述在Vue组件中,beforeDestroy钩子函数和destroyed钩子函数通常用于哪些不同场景的清理工作,并举例说明。
26.5万 热度难度
前端开发Vue

知识考点

AI 面试

面试题答案

一键面试

beforeDestroy钩子函数

  1. 场景:在实例销毁之前调用。此时实例仍然完全可用,可用于解绑自定义事件监听器、取消定时器等操作,因为此时组件实例还存在,能正常访问组件的属性和方法。
  2. 举例
<template>
  <div>
    <button @click="startTimer">开始定时器</button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      timer: null
    };
  },
  methods: {
    startTimer() {
      this.timer = setInterval(() => {
        console.log('定时器在运行');
      }, 1000);
    }
  },
  beforeDestroy() {
    if (this.timer) {
      clearInterval(this.timer);
      console.log('定时器在beforeDestroy中被清除');
    }
  }
};
</script>

destroyed钩子函数

  1. 场景:在实例销毁后调用。此时,所有的指令都被解绑,所有的事件监听器被移除,子实例也都被销毁。通常用于一些需要在组件完全销毁后执行的操作,比如打印日志记录组件已销毁等。
  2. 举例
<template>
  <div>
    <p>这是一个示例组件</p>
  </div>
</template>

<script>
export default {
  destroyed() {
    console.log('组件已销毁,此日志记录在destroyed钩子中');
  }
};
</script>