vue3 销毁定时器
时间: 2023-09-29 19:04:06 浏览: 109
在 Vue 3 中销毁定时器可以使用 `onBeforeUnmount` 钩子函数来实现。首先,在组件中定义一个定时器变量,然后在 `onMounted` 钩子函数中启动定时器,在 `onBeforeUnmount` 钩子函数中清除该定时器。
以下是一个示例代码:
```vue
<template>
<div>
<p>{{ count }}</p>
</div>
</template>
<script>
import { ref, onMounted, onBeforeUnmount } from 'vue';
export default {
setup() {
const count = ref(0);
let timer;
onMounted(() => {
// 启动定时器
timer = setInterval(() => {
count.value++;
}, 1000);
});
onBeforeUnmount(() => {
// 清除定时器
clearInterval(timer);
});
return {
count,
};
},
};
</script>
```
在上面的代码中,`onMounted` 钩子函数会在组件挂载后立即执行,启动了一个每秒加一的定时器。而 `onBeforeUnmount` 钩子函数会在组件即将销毁之前执行,清除定时器。
这样,在组件销毁时,定时器也会被自动清除,避免了潜在的内存泄漏问题。