<template>
<div>
<span>{{ hourString.substring(0, 1) }}</span>
<span>{{ hourString.substring(1, 2) }}</span>
<span>:</span>
<span>{{ minuteString.substring(0, 1) }}</span>
<span>{{ minuteString.substring(1, 2) }}</span>
<span>:</span>
<span>{{ secondString.substring(0, 1) }}</span>
<span>{{ secondString.substring(1, 2) }}</span>
</div>
</template>
<script>
export default {
data() {
return {
hour: "",
minute: "",
second: "",
promiseTimer: "",
}
},
props: {
remainTime: Number,
},
watch: {
remainTime: {
handler() {
if (this.remainTime > 0) {
this.hour = Math.floor((this.remainTime / 3600) % 24)
this.minute = Math.floor((this.remainTime / 60) % 60)
this.second = Math.floor(this.remainTime % 60)
this.countDowm()
}
},
deep: true,
},
},
mounted() {
if (this.remainTime > 0) {
this.hour = Math.floor((this.remainTime / 3600) % 24)
this.minute = Math.floor((this.remainTime / 60) % 60)
this.second = Math.floor(this.remainTime % 60)
this.countDowm()
}
},
methods: {
countDowm() {
var self = this
clearInterval(this.promiseTimer)
this.promiseTimer = setInterval(function() {
if (self.hour === 0) {
if (self.minute !== 0 && self.second === 0) {
self.second = 59
self.minute -= 1
} else if (self.minute === 0 && self.second === 0) {
self.second = 0
self.$emit("countDowmEnd", true)
clearInterval(self.promiseTimer)
} else {
self.second -= 1
}
} else {
if (self.minute !== 0 && self.second === 0) {
self.second = 59
self.minute -= 1
} else if (self.minute === 0 && self.second === 0) {
self.hour -= 1
self.minute = 59
self.second = 59
} else {
self.second -= 1
}
}
}, 1000)
},
formatNum(num) {
if (num == 0) {
num = "0"
}
return num < 10 ? "0" + num : "" + num
},
},
computed: {
hourString() {
return this.formatNum(this.hour)
},
minuteString() {
return this.formatNum(this.minute)
},
secondString() {
return this.formatNum(this.second)
},
},
}
</script>
vue-倒计时组件-可自定义样式
于 2020-07-24 17:07:36 首次发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)