记录一下代码,方便以后使用
- 做了以下修改
- 修改了formateDate方法中传入参数这个不合理的地方
- 给定时器增加了间隔时间
- 增加了取消定时器的方法
<!-- template中的代码 -->
<span>当前时间:{{ nowTime }}</span>
// script 中的代码
import { ref, onMounted, onBeforeUnmount } from 'vue'
/**
* 显示实时时间
*/
const nowTime = ref('')
/**
* 将小于10的数字前面补0
* @function
* @param {number} value
* @returns {string} 返回补0后的字符串
*/
const complement = (value: number): string => {
return value < 10 ? `0${value}` : value.toString()
}
/**
* 格式化时间为XXXX年XX月XX日XX时XX分XX秒
* @function
* @returns {string} 返回格式化后的时间
*/
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())
const week = '星期' + '日一二三四五六'.charAt(time.getDay());
return `${year}年${month}月${day}日 ${hour}:${minute}:${second}`
}
let timer = 0
/**
* 设置定时器
*/
onMounted(() => {
timer = setInterval(() => {
nowTime.value = formateDate()
}, 1000)
})
/**
* 取消定时器
*/
onBeforeUnmount(() => {
clearInterval(timer) //清除定时器
timer = 0
})
// 结果
当前时间:2024年01月12日 21:34:48