一个页面多个定时器,刚接到这个需求的时候,我觉着这不是简简单单,一写下来,懵了
一直在找资料(以我这个才智,找到了也看不懂),某一个时刻突发奇想,搞了个demo,给各位有这个需求的提供个思路
一般开始的时间戳都是后端返回的,这里就是模拟一下
如果后端返回的是 (xxxx-xx-xx xx:xx:xx) 就使用+new Date(xxxx-xx-xx xx:xx:xx)转一下就好
list:[
{
timeA: 1658325600000
},
{
timeA: 1658329200000
},
{
timeA: 1658331494000
},
]
倒计时
我这里 时分秒是分开了,因为我这要分开写一些样式, 没有需求的话,写一起 拼起来就好
setTimeH(starttime) {
let nowTime = +new Date()
let times = (starttime - nowTime) / 1000
let h = Math.floor(times / 60 /60 % 24)
return h < 10 ? '0' + h : h
},
setTimeM(starttime) {
let nowTime = +new Date()
let times = (starttime - nowTime) / 1000
let m = Math.floor(times / 60 % 60)
return m < 10 ? '0' + m : m
},
setTimeS(starttime) {
let nowTime = +new Date()
let times = (starttime - nowTime) / 1000
let s = Math.floor(times % 60)
return s < 10 ? '0' + s : s
},
定时器执行
...调接口获取数据后执行, 这里就是演示一下
setInterval(() => {
this.list.forEach((val) => {
this.$set(val, 'countDownH', this.setTimeH(val.timeA))
this.$set(val, 'countDownM', this.setTimeM(val.timeA))
this.$set(val, 'countDownS', this.setTimeS(val.timeA))
});
},1000)
template上就直接 for循环数据, 例如
<div v-for="(item,index) in list" :key="index">{{ item.countDownH }}-{{ item.countDownM }}--{{ item.countDownS }}</div>
最后可以在vue ( beforeDestroy,destroyed)钩子里,销毁定时器
demo效果图
没搞动图, 希望能给各位大佬提给点思路, 这个方法有什么问题、错误,随时指正哦