模仿vantUI的倒計(jì)時(shí)組件逗宁,自己寫(xiě)了個(gè)簡(jiǎn)易的
<template>
<span>{{ countDown }}</span>
</template>
<script>
export default {
data() {
return {
thisTime: 0,
timer: '', // 公共定時(shí)器
countDown: '', // 倒計(jì)時(shí)
};
},
props: {
// 倒計(jì)時(shí)間總秒數(shù)
time: {
default: '0',
},
// 格式 YY 年 MM 月 DD 天數(shù) hh 小時(shí) mm 分鐘 ss 秒數(shù)
format: {
default: 'hh:mm:ss',
},
// 遞增模式
add: {
default: false,
},
// 自動(dòng)補(bǔ)足兩位數(shù)
padStart: {
default: true,
},
},
methods: {
// 處理格式
handleFormat() {
let unitArr = [
{ name: 'YY', unit: 12 * 30 * 24 * 60 * 60 * 1 },
{ name: 'MM', unit: 30 * 24 * 60 * 60 * 1 },
{ name: 'DD', unit: 24 * 60 * 60 * 1 },
{ name: 'hh', unit: 60 * 60 * 1 },
{ name: 'mm', unit: 60 * 1 },
{ name: 'ss', unit: 1 },
];
let _format = this.format;
let _time = this.thisTime;
let str = '';
unitArr.forEach(item => {
let arr = _format.split(item.name);
if (arr.length === 2) {
let count = String(Math.floor(_time / item.unit));
this.padStart && (count = count.padStart(2, '0'));
str += arr[0] + count;
_time = _time - count * item.unit;
_format = arr[1];
}
});
str += _format;
this.countDown = str;
},
// 倒計(jì)時(shí)
toCountDown() {
const that = this;
clearInterval(this.timer);
this.timer = setInterval(function () {
console.log('定時(shí)器');
that.add ? (that.thisTime += 1) : (that.thisTime -= 1);
that.handleFormat();
if (that.thisTime <= 0) {
clearInterval(that.timer);
that.$emit('end');
console.warn('定時(shí)結(jié)束');
}
}, 1000);
},
},
watch: {
time: {
handler(val) {
this.thisTime = this.time;
this.handleFormat();
console.log(this.format);
if (this.time > 0) {
this.toCountDown();
}
},
immediate: true,
},
},
beforeDestroy() {
clearInterval(this.timer);
},
};
</script>
使用方法:
<countDown
format="hh 小時(shí) mm 分鐘 ss 秒"
:time="countDown"
@end="countDownEnd"
/>
<!--
time [string] 倒計(jì)時(shí)間總秒數(shù)
format [string] 格式 YY 年 MM 月 DD 天數(shù) hh 小時(shí) mm 分鐘 ss 秒數(shù)
add [boolean] 遞增模式,默認(rèn)false
padStart [boolean] 是否自動(dòng)補(bǔ)足兩位數(shù),默認(rèn)true
-->
<script>
export default {
data() {
return {
countDown: 0, // 倒計(jì)時(shí)
};
},
methods: {
// 倒計(jì)時(shí)結(jié)束
countDownEnd() {
console.log('倒計(jì)時(shí)結(jié)束');
},
},
mounted() {
// 測(cè)試定時(shí)器
setTimeout(() => {
this.countDown = 15;
}, 1000);
},
};
</script>