业务需要可自由控制的倒计时组件, 又不想引入庞大的组件库, 翻遍网络也没有深的我心的, 主要是网络上的都太个性化, 不够通用, 而且少有能自由控制的, 遂自己写.
功能介绍:
可以随时更改endTime来重置倒计时
参数:
endTime, 结束时间戳, 控制倒计时时间
事件:
stop, 倒计时结束时的回调函数
<template>
<span>{{
hourString + ":" + minuteString + ":" + secondString
}}</span>
</template>
<script>
export default {
data() {
return {
hour: "",
minute: "",
second: "",
oTimer: "",
};
},
props: {
endTime: {
// 倒计结束时间戳
default: "",
},
},
mounted() {
this.countDowm();
},
updated() {
},
methods: {
countDowm() {
clearInterval(this.oTimer);
// 计算remainTime
var remainTime = this.endTime - parseInt(Date.now()/1000)
console.log("倒计时重置")
this.temp(remainTime)
this.oTimer = setInterval(() => {
remainTime--
this.temp(remainTime)
if (remainTime <= 0){
clearInterval(this.oTimer);
this.$emit("stop")
return
}
}, 1000);
},
temp(remainTime){
this.hour = Math.floor((remainTime / 3600) % 24);
this.minute = Math.floor((remainTime / 60) % 60);
this.second = Math.floor(remainTime % 60);
},
formatNum(num) {
if (!num){
return "00"
}
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);
},
},
watch: {
endTime (newval, oldval) {
this.countDowm()
}
}
};
</script>
如果帮到了你, 可否给个赞呢?