MST

星途 面试题库

面试题:Vue组件销毁时常用的生命周期钩子是什么以及它的作用

在Vue组件销毁时,有一个常用的生命周期钩子函数。请说出这个钩子函数的名称,并简要描述它在组件销毁过程中通常用于执行哪些类型的操作,例如清理定时器、解绑事件等场景下的具体应用。
39.0万 热度难度
前端开发Vue

知识考点

AI 面试

面试题答案

一键面试

钩子函数名称

beforeDestroy(Vue 2.x) 或 beforeUnmount(Vue 3.x)。

通常执行的操作

  1. 清理定时器
    • 在组件中,如果使用了 setIntervalsetTimeout 创建定时器,在组件销毁时需要清理,避免内存泄漏。例如在 Vue 2.x 中:
    <template>
      <div></div>
    </template>
    <script>
    export default {
      data() {
        return {
          timer: null
        };
      },
      created() {
        this.timer = setInterval(() => {
          console.log('定时器在运行');
        }, 1000);
      },
      beforeDestroy() {
        clearInterval(this.timer);
        this.timer = null;
      }
    };
    </script>
    
    • 在 Vue 3.x 中:
    <template>
      <div></div>
    </template>
    <script setup>
    import { onBeforeUnmount } from 'vue';
    let timer = null;
    timer = setInterval(() => {
      console.log('定时器在运行');
    }, 1000);
    onBeforeUnmount(() => {
      clearInterval(timer);
      timer = null;
    });
    </script>
    
  2. 解绑事件
    • 当在组件中手动绑定了 DOM 事件(例如通过 addEventListener),在组件销毁时要解绑。比如在 Vue 2.x 中:
    <template>
      <div ref="myDiv"></div>
    </template>
    <script>
    export default {
      mounted() {
        this.$refs.myDiv.addEventListener('click', this.handleClick);
      },
      methods: {
        handleClick() {
          console.log('点击了 div');
        }
      },
      beforeDestroy() {
        this.$refs.myDiv.removeEventListener('click', this.handleClick);
      }
    };
    </script>
    
    • 在 Vue 3.x 中:
    <template>
      <div ref="myDiv"></div>
    </template>
    <script setup>
    import { onBeforeUnmount, ref } from 'vue';
    const myDiv = ref(null);
    const handleClick = () => {
      console.log('点击了 div');
    };
    myDiv.value.addEventListener('click', handleClick);
    onBeforeUnmount(() => {
      myDiv.value.removeEventListener('click', handleClick);
    });
    </script>
    
  3. 取消网络请求
    • 如果组件发起了网络请求(例如使用 axios),并且在组件销毁时请求还未完成,需要取消请求。在 Vue 2.x 中,假设使用 axios
    <template>
      <div></div>
    </template>
    <script>
    import axios from 'axios';
    export default {
      data() {
        return {
          cancelToken: null
        };
      },
      created() {
        this.cancelToken = axios.CancelToken.source();
        axios.get('/api/data', {
          cancelToken: this.cancelToken.token
        }).then(response => {
          console.log(response.data);
        }).catch(error => {
          if (!axios.isCancel(error)) {
            console.error('请求错误', error);
          }
        });
      },
      beforeDestroy() {
        this.cancelToken.cancel('组件销毁,取消请求');
      }
    };
    </script>
    
    • 在 Vue 3.x 中同理,只是写法上可能使用 setup 语法:
    <template>
      <div></div>
    </template>
    <script setup>
    import axios from 'axios';
    import { onBeforeUnmount } from 'vue';
    const cancelToken = axios.CancelToken.source();
    axios.get('/api/data', {
      cancelToken: cancelToken.token
    }).then(response => {
      console.log(response.data);
    }).catch(error => {
      if (!axios.isCancel(error)) {
        console.error('请求错误', error);
      }
    });
    onBeforeUnmount(() => {
      cancelToken.cancel('组件销毁,取消请求');
    });
    </script>