Files
lc_frontend/src/views/screen/composables/useTimeManager.ts

43 lines
1.2 KiB
TypeScript
Raw Normal View History

2025-10-17 10:31:13 +08:00
import { ref, onUnmounted } from 'vue'
export function useTimeManager() {
const currentTime = ref<string>('')
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()
}
}
}