效果图为:
前端:
<template>
<div>{{ currentTime }}</div>
<div class="realtime_day">{{ currentDay }}</div>
</template>
js:
<script lang="ts" setup>
import { ref, reactive, onMounted, onUnmounted } from "vue";
const currentTime = ref('');
const currentDay = ref('');
let timer = null;
onMounted(() => {
startTimer();
});
onUnmounted(() => {
stopTimer();
});
function startTimer() {
timer = setInterval(() => {
const dt = new Date();
const y = dt.getFullYear();
const mt = dt.getMonth() + 1;
const day = dt.getDate();
const h = dt.getHours().toString().padStart(2, '0');
const m = dt.getMinutes().toString().padStart(2, '0');
const s = dt.getSeconds().toString().padStart(2, '0');
currentTime.value = `${h} : ${m} : ${s}`;
currentDay.value = `${y} / ${mt} / ${day}`;
}, 10);
}
function stopTimer() {
clearInterval(timer);
}
</script>