插件窝 干货文章 Vue3组件路由切换后定时器未销毁?如何正确管理组件生命周期和定时器?

Vue3组件路由切换后定时器未销毁?如何正确管理组件生命周期和定时器?

timer 定时器 使用 console 69    来源:    2025-03-22

在Vue 3中,组件路由切换时,如果定时器未正确销毁,可能会导致内存泄漏或意外的行为。为了正确管理组件的生命周期和定时器,你可以采取以下措施:

1. 使用 onMountedonUnmounted 生命周期钩子

Vue 3 提供了 onMountedonUnmounted 生命周期钩子,你可以在这些钩子中分别创建和销毁定时器。

import { onMounted, onUnmounted } from 'vue';

export default {
  setup() {
    let timer;

    onMounted(() => {
      timer = setInterval(() => {
        console.log('Timer is running...');
      }, 1000);
    });

    onUnmounted(() => {
      if (timer) {
        clearInterval(timer);
        console.log('Timer cleared.');
      }
    });

    return {};
  },
};

2. 使用 watchEffect 自动清理

watchEffect 是 Vue 3 中的一个响应式 API,它会在依赖项变化时自动重新运行,并且在组件卸载时自动清理副作用。

import { watchEffect } from 'vue';

export default {
  setup() {
    watchEffect((onCleanup) => {
      const timer = setInterval(() => {
        console.log('Timer is running...');
      }, 1000);

      onCleanup(() => {
        clearInterval(timer);
        console.log('Timer cleared.');
      });
    });

    return {};
  },
};

3. 使用 refwatch 结合

如果你需要在特定条件下启动或停止定时器,可以使用 refwatch 结合的方式来管理定时器。

import { ref, watch, onUnmounted } from 'vue';

export default {
  setup() {
    const isActive = ref(true);
    let timer;

    watch(isActive, (newVal) => {
      if (newVal) {
        timer = setInterval(() => {
          console.log('Timer is running...');
        }, 1000);
      } else {
        if (timer) {
          clearInterval(timer);
          console.log('Timer cleared.');
        }
      }
    }, { immediate: true });

    onUnmounted(() => {
      if (timer) {
        clearInterval(timer);
        console.log('Timer cleared.');
      }
    });

    return {
      isActive,
    };
  },
};

4. 使用 beforeUnmount 钩子

如果你仍然使用 Options API,可以在 beforeUnmount 钩子中清理定时器。

export default {
  data() {
    return {
      timer: null,
    };
  },
  mounted() {
    this.timer = setInterval(() => {
      console.log('Timer is running...');
    }, 1000);
  },
  beforeUnmount() {
    if (this.timer) {
      clearInterval(this.timer);
      console.log('Timer cleared.');
    }
  },
};

总结

  • 使用 onMountedonUnmounted:这是 Vue 3 推荐的方式,适用于 Composition API。
  • 使用 watchEffect:自动清理副作用,适合简单的场景。
  • 使用 refwatch:适合需要动态控制定时器的场景。
  • 使用 beforeUnmount:适用于 Options API。

通过这些方法,你可以确保在组件卸载时正确销毁定时器,避免内存泄漏和其他潜在问题。