import { ref, onUnmounted } from 'vue' export function useTimeManager() { const currentTime = ref('') let timeInterval: NodeJS.Timeout | null = null const updateTime = (): void => { const now = new Date() const year = now.getFullYear() const month = String(now.getMonth() + 1).padStart(2, '0') const day = String(now.getDate()).padStart(2, '0') const weekdays = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'] const weekday = weekdays[now.getDay()] const hours = String(now.getHours()).padStart(2, '0') const minutes = String(now.getMinutes()).padStart(2, '0') const seconds = String(now.getSeconds()).padStart(2, '0') currentTime.value = `${year}年${month}月${day}日 ${weekday} ${hours}:${minutes}:${seconds}` } const startTimeUpdate = (): void => { updateTime() timeInterval = setInterval(updateTime, 1000) } const stopTimeUpdate = (): void => { if (timeInterval) { clearInterval(timeInterval) timeInterval = null } } return { currentTime, startTimeUpdate, stopTimeUpdate, // 返回清理函数,让调用方在组件卸载时调用 cleanup: () => { stopTimeUpdate() } } }