delEvnents

This commit is contained in:
龚皓
2024-11-26 16:09:50 +08:00
parent f0b6d900ac
commit 207913a253
2 changed files with 90 additions and 12 deletions

View File

@@ -0,0 +1,59 @@
import {ref} from 'vue'
import { defineStore } from 'pinia';
// 定义回调类型
type TimerCallback = () => void;
export const useGlobalTimerStore = defineStore('globalTimer', () => {
const intervalId = ref<number | null>(null); // 定时器 ID
const refreshIntervalMs = ref(300000); // 默认刷新间隔5 分钟)
const registeredCallbacks = ref<TimerCallback[]>([]); // 注册的回调函数列表
// 注册回调
const registerCallback = (callback: TimerCallback) => {
if (typeof callback === 'function' && !registeredCallbacks.value.includes(callback)) {
registeredCallbacks.value.push(callback);
}
};
// 注销回调
const unregisterCallback = (callback: TimerCallback) => {
const index = registeredCallbacks.value.indexOf(callback);
if (index !== -1) {
registeredCallbacks.value.splice(index, 1);
}
};
// 启动定时器
const startTimer = () => {
if (!intervalId.value) {
intervalId.value = window.setInterval(() => {
registeredCallbacks.value.forEach((callback) => callback());
}, refreshIntervalMs.value);
}
};
// 停止定时器
const stopTimer = () => {
if (intervalId.value) {
clearInterval(intervalId.value);
intervalId.value = null;
}
};
// 设置定时器间隔
const setRefreshInterval = (interval: number) => {
refreshIntervalMs.value = interval;
stopTimer();
startTimer();
};
return {
refreshIntervalMs,
registerCallback,
unregisterCallback,
startTimer,
stopTimer,
setRefreshInterval,
};
});