1.声明变量
data() {
return {
nowTime: '',
nowWeek: '',
nowDate: '',
newTimer: '', //定时器
}
},
2.调取获取时间的方法并且清除定时器后再设置定时获取时间的任务
mounted() {
this.timerOneScondRun() //执行日期函数
clearInterval(this.newTimer) //清除定时器
// 定时获取时间
this.newTimer = setInterval(this.timerOneScondRun, 1000)
},
3.获取时间
//获取时间
timerOneScondRun() {
let date = new Date()
// 日期格式 2022.05.31.
this.nowDate =
date.getFullYear() +
'.' +
(date.getMonth() + 1 >= 10 ? date.getMonth() + 1 : '0' + (date.getMonth() + 1)) +
'.' +
(date.getDate() >= 10 ? date.getDate() : '0' + date.getDate())
// 时间格式 12:11:27
this.nowTime =
date.getHours() +
':' +
(date.getMinutes() >= 10 ? date.getMinutes() : '0' + date.getMinutes()) +
':' +
(date.getSeconds() >= 10 ? date.getSeconds() : '0' + date.getSeconds())
// 星期
let weeks = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六']
this.nowWeek = weeks[date.getDay()]
},
4.在导航离开渲染该组件的对应路由时清除定时任务
beforeRouteLeave(to, from, next) {
// 离开组件时停掉定时器,节省内存
clearInterval(this.newTimer)
next()
},
效果
实时刷新时间