index.vue 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. <template>
  2. <div class="timeNow">
  3. <span class="item date">{{ timeNow.date }}</span>
  4. <span class="item week">{{ timeNow.week }}</span>
  5. <span class="item time">{{ timeNow.time }}</span>
  6. </div>
  7. </template>
  8. <script setup lang="ts">
  9. import { ref, onUnmounted } from 'vue'
  10. defineOptions({
  11. name: 'timeNow',
  12. })
  13. // 获取现在的时间
  14. const getNowTime = () => {
  15. const now = new Date()
  16. // const year = now.getFullYear()
  17. const month = now.getMonth() + 1
  18. const day = now.getDate()
  19. const week = now.getDay()
  20. const hour = now.getHours().toString().padStart(2, '0')
  21. const minute = now.getMinutes().toString().padStart(2, '0')
  22. const second = now.getSeconds().toString().padStart(2, '0')
  23. const weekMap = ['日', '一', '二', '三', '四', '五', '六']
  24. return {
  25. date: `${month}月${day}日`,
  26. week: `星期${weekMap[week]}`,
  27. time: `${hour}:${minute}:${second}`,
  28. }
  29. }
  30. const timeNow = ref(getNowTime())
  31. // 每秒更新一次时间
  32. const timer = setInterval(() => {
  33. timeNow.value = getNowTime()
  34. }, 1000)
  35. // 组件卸载时清除定时器
  36. onUnmounted(() => {
  37. clearInterval(timer)
  38. })
  39. </script>
  40. <style scoped lang="less">
  41. .timeNow {
  42. font-size: 14px;
  43. font-weight: 600;
  44. padding: 0 10px;
  45. user-select: none;
  46. .item {
  47. display: inline-block;
  48. padding: 0 3px;
  49. }
  50. .time {
  51. width: 75px;
  52. display: inline-block;
  53. letter-spacing: 2px;
  54. }
  55. }
  56. </style>