stanley工具網(wǎng)站開發(fā)品牌策略
記錄一下代碼,方便以后使用
參考的文章鏈接
- 做了以下修改
- 修改了formateDate方法中傳入?yún)?shù)這個不合理的地方
- 給定時器增加了間隔時間
- 增加了取消定時器的方法
<!-- template中的代碼 -->
<span>當(dāng)前時間:{{ nowTime }}</span>
// script 中的代碼
import { ref, onMounted, onBeforeUnmount } from 'vue'
/*** 顯示實(shí)時時間*/const nowTime = ref('')
/*** 將小于10的數(shù)字前面補(bǔ)0* @function* @param {number} value* @returns {string} 返回補(bǔ)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
/*** 設(shè)置定時器*/
onMounted(() => {timer = setInterval(() => {nowTime.value = formateDate()}, 1000)
})
/*** 取消定時器*/
onBeforeUnmount(() => {clearInterval(timer) //清除定時器timer = 0
})
// 結(jié)果
當(dāng)前時間:2024年01月12日 21:34:48