代码案例
<script lang="ts" setup>
import { ref,onMounted } from 'vue';
const timer = ref()
const date = ref("")//年月日
const moreTime = ref("")//时分秒
onMounted(()=>{
//创建定时器1秒执行一次
timer.value = setInterval(() => {
formateDate()
}, 1000)
})
//取消定时器
onBeforeUnmount(() => {
clearInterval(timer.value) //清除定时器
})
//获取当前时间
const formateDate = () => {
const time = new Date()
const year = time.getFullYear()
const month = complement(time.getMonth() + 1)
const day = complement(time.getDate())
const hour = complement(time.getHours())
const minute = complement(time.getMinutes())
const second = complement(time.getSeconds())
moreTime.value = `${hour}:${minute}:${second}`
date.value = `${year}-${month}-${day}`
}
//当时间为个位数的时候,在数字前加0
const complement = (value: number): string => {
return value < 10 ? `0${value}` : value.toString()
}
</script>
运行结果
![](https://i-blog.csdnimg.cn/direct/7c2d8a729238428086ff94dae6555bd3.png)