一、封装组件countDown.vue
<template>
<div
:endTime="endTime"
style="display: flex; justify-content: center; align-items: center"
>
<div class="blackBox">
{{ tians }}
</div>
<div class="whiteFont">天</div>
<div class="blackBox">{{ hours }}</div>
<div class="whiteFont">时</div>
<div class="blackBox">{{ minutes }}</div>
<div class="whiteFont">分</div>
</div>
</template>
<script>
export default {
name: 'countDown',
data () {
return {
tians: 0,
hours: 0,
minutes: 0,
pageTimer: {}
}
},
props: {
endTime: {
type: Number,
default: 0
}
},
mounted () {
this.countdowm(this.endTime)
},
watch: {
endTime (curVal, oldVal) {
if (this.pageTimer) {
// 清除所有的定时器,防止传过来的值变化出现闪烁的问题
for (const each in this.pageTimer) {
clearInterval(this.pageTimer[each])
}
}
this.countdowm(curVal, oldVal)
}
},
methods: {
countdowm (timestamp, oldtime) {
const self = this
this.pageTimer.timer1 = setInterval(function () {
const nowTime = new Date()
const endTime = new Date(timestamp * 1000)
const t = endTime.getTime() - nowTime.getTime()
if (t > 0) {
let tian = Math.floor(t / 86400000)
let hour = Math.floor((t / 3600000) % 24)
let min = Math.floor((t / 60000) % 60)
tian = tian < 10 ? '0' + tian : tian
hour = hour < 10 ? '0' + hour : hour
min = min < 10 ? '0' + min : min
self.tians = tian
self.hours = hour
self.minutes = min
} else {
clearInterval(self.pageTimer.timer1)
self.tians = 0
self.hours = 0
self.minutes = 0
}
}, 1000)
}
}
}
</script>
<style lang="less" scoped>
.blackBox {
width: 44px;
height: 44px;
background: #272931;
border-radius: 12px;
font-size: 24px;
font-family: DIN Alternate-Bold, DIN Alternate;
font-weight: bold;
color: #ffffff;
line-height: 44px;
text-align: center;
}
.whiteFont {
width: 24px;
height: 44px;
font-size: 24px;
font-family: PingFang SC-Medium, PingFang SC;
font-weight: 500;
color: #ffffff;
line-height: 44px;
text-align: center;
margin: 0 8px;
}
</style>
二、引用组件
<count-down :endTime="1692460800" />
import countDown from './module/countDown.vue'
components: {
countDown
}
三、时间戳转换