import {defineStore} from "pinia"; import {useMainLayoutStore} from "~/strores/UseMainLayoutStore"; import dayjs from "dayjs"; export const useDataStore = defineStore('DataStore', { state: () => ({ data: {}, dataHistory: {...defaultDataHistory}, timer: null as any, }), actions: { setData(type: string, data: any) { //不存在则添加,存在则更新 this.data[type] = data }, startTimer() { if (this.timer) return; // 防止重复启动定时器 this.timer = setInterval(() => { // 每秒将 data 中的数据添加到 dataHistory 中 this.addDataToHistory(); }, 5000); }, stopTimer() { if (this.timer) { clearInterval(this.timer); this.timer = null; } }, addDataToHistory() { const currentTime = dayjs().format('MM-DD HH:mm:ss'); for (const key in this.data) { const value = this.data[key]; if (!this.dataHistory.data[key]) { this.dataHistory.data[key] = []; } this.dataHistory.data[key].push(value) } this.dataHistory.times.push(currentTime); } }, persist: { storage: persistedState.sessionStorage, }, }) export type dataType = { [key: string]: string; }; export type dataHistoryType = { times: string[], data: dataHistoryDataType, } type dataHistoryDataType = { [key: string]: string[] } const defaultDataHistory: dataHistoryType = { times: [], data: {} }