使用場(chǎng)景:
一般多個(gè)定時(shí)器同時(shí)使用的場(chǎng)景主要應(yīng)用在限時(shí)活動(dòng)或者限時(shí)搶購(gòu)商品等担忧,如一個(gè)頁(yè)面存在多個(gè)商品级零,且每個(gè)商品都有獨(dú)立的限時(shí)搶購(gòu)時(shí)間秘遏,因此就會(huì)遇到多個(gè)定時(shí)器同步刷新倒計(jì)時(shí)
限時(shí)搶購(gòu)使用場(chǎng)景
這次就用簡(jiǎn)單數(shù)據(jù)來模擬多個(gè)定時(shí)器同步刷新實(shí)現(xiàn)效果,效果不同原理一樣
模擬效果
html
<ul>
<li v-for="(item,index) in timeLists" :key="index">
<span>節(jié)日名稱:{{item.name}} </span>
<span>節(jié)日時(shí)間:{{item.time}} </span>
<span>剩余時(shí)間:{{item.residueTime}} </span>
</li>
</ul>
js
var timeId
export default {
name: '',
data () {
return {
timeLists: []
}
},
created () { // 實(shí)例被創(chuàng)建之后執(zhí)行代碼
this.getTimeList()
},
beforeDestroy () { //組件的銷毀
clearInterval(timeId) // 清除定時(shí)器
timeId=null
},
methods: {
//獲取各節(jié)日時(shí)間
getTimeList () {
let timeArr = [{ //模擬數(shù)據(jù) 屆時(shí)即為后端請(qǐng)求接口獲取
name: '元旦 ', time: '2020-01-01 00:00:00', residueTime: '' }, {
name: '新年 ', time: '2020-01-25 00:00:00', residueTime: '' }, {
name: '元宵節(jié)', time: '2020-02-08 00:00:00', residueTime: '' }]
this.timeLists = timeArr
this.setIntervalTime() // 調(diào)取倒計(jì)時(shí)
},
// 設(shè)置定時(shí)器做倒計(jì)時(shí)
setIntervalTime () {
timeId = setInterval(() => {
this.timeLists.forEach(item => {
item.residueTime = this.getResidueTime(item.time)
})
}, 1000)
},
// 獲取剩余時(shí)間
getResidueTime (end) {
let nowtime = new Date().getTime(); // 當(dāng)前時(shí)間 毫秒數(shù)
let endTime = Date.parse(new Date(end.replace(/-/g, "/"))); //結(jié)束時(shí)間 毫秒數(shù)
let totalSeconds = (endTime - nowtime) / 1000; // 結(jié)束時(shí)間-當(dāng)前時(shí)間 = 剩余多少時(shí)間
let day = parseInt(totalSeconds / 3600 / 24); //天
let hour = parseInt((totalSeconds / 3600) % 24); //時(shí)
let minute = parseInt((totalSeconds / 60) % 60); //分
let second = parseInt(totalSeconds % 60); //秒
let residueTime ="倒計(jì)時(shí):" + day + "天 " + hour + "時(shí) " + minute + "分 " + second + "秒";
hour = this.addZero(hour)
minute = this.addZero(minute)
second = this.addZero(second)
if (totalSeconds < 0) {
residueTime = '時(shí)間到'
}
return residueTime
},
// 補(bǔ)齊格式不滿10加0
addZero (n) {
return n < 10 ? '0' + n : n
},
}
}