Vue3 实时显示时间

记录一下代码,方便以后使用

参考的文章链接

  • 做了以下修改
    1. 修改了formateDate方法中传入参数这个不合理的地方
    2. 给定时器增加了间隔时间
    3. 增加了取消定时器的方法
<!-- 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
})
// 结果
当前时间:2024011221:34:48
  • 9
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值