1.创建ts文件
路径:src/utils/timer.ts
完整代码:
import { onUnmounted } from 'vue'
type TimerCallback = (...args: any[]) => void
export function useGlobalTimer() {
const timers: Map<number, NodeJS.Timeout> = new Map()
// 创建定时器
const setInterval = (
callback: TimerCallback,
delay: number,
...args: any[]
): number => {
const timerId = window.setInterval(() => callback(...args), delay)
timers.set(timerId, timerId)
return timerId
}
// 清除单个定时器
const clearInterval = (timerId: number) => {
window.clearInterval(timerId)
timers.delete(timerId)
}
// 清除所有定时器
const clearAll = () => {
timers.forEach((timer) => {
window.clearInterval(timer)
})
timers.clear()
}
// 组件卸载时自动清理
onUnmounted(clearAll)
return {
setInterval,
clearInterval,
clearAll
}
}
2.挂载到全局属性
路径:src/main.ts
完整代码:
import { createApp } from 'vue'
import App from './App.vue'
import { useGlobalTimer } from './utils/timer'
const app = createApp(App)
// 挂载到全局属性
app.config.globalProperties.$timer = useGlobalTimer()
app.mount('#app')
3.使用方式:
引入全局方法:
import {getCurrentInstance } from 'vue'
const { proxy } = getCurrentInstance()!
使用:
创建定时器:
proxy!.$timer.setInterval(() => { // 需要定时循环的内容 // }, 时间);
清除定时器:
proxy!.$timer.clearInterval(timerId)
完整代码:
<template>
</template>
<script setup lang="ts" name="index">
import {ref, onMounted, onUnmounted, getCurrentInstance} from 'vue';
const {proxy} = getCurrentInstance()!
let timerId: number
onMounted(() => {
//创建定时器
timerId = proxy!.$timer.setInterval(() => {
//循环内容
}, //循环时间);
});
onUnmounted(() => {
//清除定时器
proxy!.$timer.clearInterval(timerId)
})
</script>
<style scoped lang="scss">
</style>