<template>
    <div class="text-h6 text-weight-bold">
        {{ nowDateTime }}
    </div>
</template>
<script setup lang='ts'>
import { ref, onMounted, onBeforeUnmount } from 'vue'

const nowDateTime = ref();
//定义 timer 初始值及类型
let timer: NodeJS.Timer | null = null

// 当前时间
const getNowTime = () => {
    const date = new Date();
    let year = date.getFullYear();
    let month = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1;
    let day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
    let hh = date.getHours() < 10 ? '0' + date.getHours() : date.getHours();
    let mm = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes();
    let ss = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds();
    nowDateTime.value = year + '年' + month + '月' + day + '日  ' + '星期' + '日一二三四五六'.charAt(date.getDay()) + ' ' + hh + ':' + mm + ':' + ss;
}

onMounted(() => {
    // console.log('触发  onMounted')
    getNowTime();
    timer = setInterval(() => {
        getNowTime();
    }, 1000);
})

onBeforeUnmount(() => {
    // console.log('触发  onBeforeUnmount')
    // 清理定时器要处理 timer 的类型
    clearInterval(Number(timer))
    nowDateTime.value = null;
})

</script>