Files
Yi.Admin/Yi.Ai.Vue3/src/hooks/useTimeGreeting.ts
2025-06-17 22:37:37 +08:00

37 lines
1.1 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { ref } from 'vue';
type TimeGreeting = '凌晨' | '清晨' | '早上' | '中午' | '下午' | '傍晚' | '晚上';
// 时间分段配置按顺序排列find会返回第一个匹配项
const timeRanges: Array<[start: number, end: number, label: TimeGreeting]> = [
[0, 5, '凌晨'],
[5, 7, '清晨'],
[7, 12, '早上'],
[12, 14, '中午'],
[14, 18, '下午'],
[18, 21, '傍晚'],
[21, 24, '晚上'],
];
/**
* 获取当前时段问候语Vue组合式函数
* @returns 响应式的时段问候语
*/
export function useTimeGreeting() {
// 直接计算初始值(合并初始化逻辑)
const currentHour = new Date().getHours();
const greeting = timeRanges.find(([s, e]) => currentHour >= s && currentHour < e)?.[2] || '晚上';
// 使用ref保持响应式即使不更新组件仍可正确绑定
return ref<TimeGreeting>(greeting);
}
// 示例用法在Vue组件中
// <script setup lang="ts">
// import { useTimeGreeting } from '@/hooks/useTimeGreeting';
// const timeGreeting = useTimeGreeting();
// </script>
// <template>
// <div>{{ timeGreeting }}好,欢迎~</div>
// </template>