<template>
  <div class="timeNow">
    <span class="item date">{{ timeNow.date }}</span>
    <span class="item week">{{ timeNow.week }}</span>
    <span class="item time">{{ timeNow.time }}</span>
  </div>
</template>

<script setup lang="ts">
import { ref, onUnmounted } from 'vue'

defineOptions({
  name: 'timeNow',
})

// 获取现在的时间
const getNowTime = () => {
  const now = new Date()
  // const year = now.getFullYear()
  const month = now.getMonth() + 1
  const day = now.getDate()
  const week = now.getDay()
  const hour = now.getHours().toString().padStart(2, '0')
  const minute = now.getMinutes().toString().padStart(2, '0')
  const second = now.getSeconds().toString().padStart(2, '0')
  const weekMap = ['日', '一', '二', '三', '四', '五', '六']
  return {
    date: `${month}月${day}日`,
    week: `星期${weekMap[week]}`,
    time: `${hour}:${minute}:${second}`,
  }
}
const timeNow = ref(getNowTime())

// 每秒更新一次时间
const timer = setInterval(() => {
  timeNow.value = getNowTime()
}, 1000)

// 组件卸载时清除定时器
onUnmounted(() => {
  clearInterval(timer)
})
</script>

<style scoped lang="less">
.timeNow {
  font-size: 14px;
  font-weight: 600;
  padding: 0 10px;
  user-select: none;
  .item {
    display: inline-block;
    padding: 0 3px;
  }
  .time {
    width: 75px;
    display: inline-block;
    letter-spacing: 2px;
  }
}
</style>
