html
<template>
<div>
<p>当前时间Current Time: {{ currentTime }}</p>
</div>
</template>
<script setup>
import { ref, onBeforeUnmount, onMounted } from 'vue'
const currentTime = ref('')
let interval // 声明 interval 变量
const getToday = () => {
const datas = new Date()
const on2 = ' : '
let onS = datas.getHours()
let onF = datas.getMinutes()
let onN = datas.getSeconds()
if (onS >= 0 && onS <= 9) {
onS = '0' + onS
}
if (onF >= 0 && onF <= 9) {
onF = '0' + onF
}
if (onN >= 0 && onN <= 9) {
onN = '0' + onN
}
currentTime.value = onS + on2 + onF + on2 + onN
}
onMounted(() => {
interval = setInterval(() => {
// 将 interval 赋值为 setInterval 的返回值
getToday()
}, 1000)
})
onBeforeUnmount(() => {
clearInterval(interval) // 使用 clearInterval 清除 interval 计时器
})
</script>
<style scoped>
p {
font-size: 30px;
color: hsla(160, 100%, 37%, 1);
text-shadow: 1px 1px 1px rgb(0, 0, 0);
}
</style>