在Vue3中,如果你在路由跳转后使用了setInterval,你需要在组件销毁前手动清除它。

在组件中使用setInterval,可以通过ref来保存定时器的id,然后在组件销毁前清除它。

在组件的setup方法中,可以创建一个ref来保存定时器的id:

import { ref } from 'vue';

export default {
  setup() {
    const timerId = ref(null);

    // ...

    return {
      timerId,
      // ...
    };
  },
  // ...
}

在组件中执行setInterval时,将定时器的id保存到ref中:

import { onBeforeUnmount } from 'vue';

export default {
  setup() {
    const timerId = ref(null);

    // ...

    setInterval(() => {
      // ...
    }, 1000);

    timerId.value = setInterval(() => {
      // ...
    }, 1000);

    return {
      timerId,
      // ...
    };
  },
  // ...
}

在组件销毁前,通过onBeforeUnmount钩子函数清除定时器:

import { onBeforeUnmount } from 'vue';

export default {
  setup() {
    const timerId = ref(null);

    // ...

    setInterval(() => {
      // ...
    }, 1000);

    timerId.value = setInterval(() => {
      // ...
    }, 1000);

    onBeforeUnmount(() => {
      clearInterval(timerId.value);
    });

    return {
      timerId,
      // ...
    };
  },
  // ...
}

这样,在组件销毁前会自动清除定时器,避免了内存泄漏的问题。

vue3 路由跳转后 setInterval不销毁

原文地址: http://www.cveoy.top/t/topic/f1T 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录