问题描述:工作需要,在vuejs项目中,给定一个开始时间,根据开始时间计算用时多少,并实时在页面显示出来,即实时计时器。
实现:直接上代码
data () {
return {
start_time: '2020-10-29 14:10:00',
count_time: '00:00:00'
}
}
计算用时的函数:
methods: {
// 计算用时 startTime为开始时间 字符串格式‘2020-10-29 14:00:00’或者Date格式都可以
countTime (startTime) {
if (!startTime) return
let start_time = new Date(startTime)
let _this = this
this.timer = setInterval(() => {
let millisecond = new Date() - start_time
let h = Math.floor(millisecond / (60 * 60 * 1000))
h = h < 10 ? '0' + h : h
let min = Math.floor(millisecond % (60 * 60 * 1000) / (60 * 1000))
min = min < 10 ? '0' + min : min
let sec = Math.floor(millisecond % (60 * 60 * 1000) % (60 * 1000) / 1000)
sec = sec < 10 ? '0' + sec : sec
_this.count_time = h + ':' + min + ':' + sec
}, 1000)
},
}
函数调用:
created () {
// 调用时机根据需求
this.countTime(this.start_time)
}
页面上展示:
<div>
开始时间:{{ start_time }}
用时:{{ count_time }}
</div>
最后别忘了清除定时器:
// 在Vue实例销毁前,清除定时器
beforeDestroy () {
if (this.timer) {
clearInterval(this.timer)
}
}
2020.10.29