time.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. import {
  2. defineStore
  3. } from 'pinia'
  4. import {
  5. ref,
  6. computed
  7. } from 'vue'
  8. export const useTimeStore = defineStore('time', () => {
  9. // 状态
  10. const greeting = ref('')
  11. const currentTime = ref('')
  12. const iconClass = ref('')
  13. const themeColor = ref('')
  14. const backgroundClass = ref('')
  15. const timerId = ref(null)
  16. // 计算属性 - 组合完整问候语
  17. const fullGreeting = computed(() => {
  18. return `${greeting.value} 当前时间是 ${currentTime.value}`
  19. })
  20. // 方法 - 更新问候语和时间状态
  21. const updateGreeting = () => {
  22. const now = new Date()
  23. const hour = now.getHours()
  24. // 更新当前时间显示
  25. currentTime.value = now.toLocaleTimeString('zh-CN', {
  26. hour: '2-digit',
  27. minute: '2-digit',
  28. second: '2-digit'
  29. })
  30. // 根据小时设置不同的问候语和样式
  31. if (hour >= 5 && hour < 12) {
  32. // 早上 (5:00 - 11:59)
  33. greeting.value = "早上好,"
  34. iconClass.value = "fa fa-sun-o"
  35. themeColor.value = "#FBBF24"
  36. backgroundClass.value =
  37. "bg-gradient-to-br from-yellow-50 to-orange-50 transition-colors duration-1000"
  38. } else if (hour >= 12 && hour < 18) {
  39. // 下午 (12:00 - 17:59)
  40. greeting.value = "下午好,"
  41. iconClass.value = "fa fa-cloud"
  42. themeColor.value = "#F97316"
  43. backgroundClass.value =
  44. "bg-gradient-to-br from-orange-50 to-red-50 transition-colors duration-1000"
  45. } else if (hour >= 18 && hour < 22) {
  46. // 晚上 (18:00 - 21:59)
  47. greeting.value = "晚上好,"
  48. iconClass.value = "fa fa-moon-o"
  49. themeColor.value = "#7C3AED"
  50. backgroundClass.value =
  51. "bg-gradient-to-br from-purple-50 to-indigo-50 transition-colors duration-1000"
  52. } else {
  53. // 深夜 (22:00 - 4:59)
  54. greeting.value = "夜深了,早点休息哦,"
  55. iconClass.value = "fa fa-star-o"
  56. themeColor.value = "#1E293B"
  57. backgroundClass.value =
  58. "bg-gradient-to-br from-gray-900/5 to-gray-800/10 transition-colors duration-1000"
  59. }
  60. }
  61. // 方法 - 启动定时器
  62. const startTimer = () => {
  63. // 先更新一次
  64. updateGreeting()
  65. // 每秒更新一次
  66. timerId.value = setInterval(updateGreeting, 1000)
  67. }
  68. // 方法 - 停止定时器
  69. const stopTimer = () => {
  70. if (timerId.value) {
  71. clearInterval(timerId.value)
  72. timerId.value = null
  73. }
  74. }
  75. updateGreeting()
  76. // 暴露状态和方法
  77. return {
  78. greeting,
  79. currentTime,
  80. iconClass,
  81. themeColor,
  82. backgroundClass,
  83. fullGreeting,
  84. startTimer,
  85. stopTimer
  86. }
  87. })