倒计时组件


<template>
<view class="min-countdown" :class="countdownClass">
<rich-text :nodes="time"></rich-text>
</view>
</template>
<script>
export default {
name: 'min-countdown',
props: {
targetTime: {
type: Number,
default: 0
},
format: {
type: String,
default: '{%d}天{%h}时{%m}分{%s}'
},
countdownClass: {
type: String,
default: ''
}
},
data() {
return {
time: '00分00秒'
};
},
methods: {
init() {
setTimeout(() => {
this.getTime();
}, 1000);
},
getTime() {
let time = {};
let format = this.format;
function formatNumber(num) {
return num > 9 ? `${num}` : `0${num}`;
}
const gapTime = Math.ceil((this.targetTime - new Date().getTime()) / 1000);
if (gapTime >= 0) {
time.d = formatNumber(parseInt(gapTime / 86400));
let lastTime = gapTime % 86400;
time.h = formatNumber(parseInt(lastTime / 3600));
lastTime = lastTime % 3600;
time.m = formatNumber(parseInt(lastTime / 60));
time.s = formatNumber(lastTime % 60);
['d', 'h', 'm', 's'].forEach(item => {
const day = time[item].split('');
format = format.replace('{%' + item + '}', time[item]);
format = format.replace('{%' + item + '0}', day[0]);
format = format.replace('{%' + item + '1}', day[1]);
format = format.replace('{%' + item + '2}', day[2] ? day[2] : '0');
});
this.time = format;
this.init();
} else {
this.$emit('callback');
}
}
},
mounted() {
this.getTime();
}
};
</script>
<style scoped>
.min-countdown {
display: inline-flex;
justify-content: center;
align-items: center;
}
</style>
属性与事件


组件使用
<view class="countdown-box">
<text>距活动开始:</text>
<min-countdown v-if="startTime !== null" :targetTime="startTime" countdownClass="red" @callback="callback" :format="format"></min-countdown>
</view>
<script>
export default {
computed: {
},
components: {
},
data() {
return {
startTime:1657170789000,
format: `<div class="countdown-time-box">
<span class="time-box">{%d0}</span>
<span class="time-box ml">{%d1}</span>
<span class="time-text">天</span>
<span class="time-box">{%h0}</span>
<span class="time-box ml">{%h1}</span>
<span class="time-text">时</span>
<span class="time-box">{%m0}</span>
<span class="time-box ml">{%m1}</span>
<span class="time-text">分</span>
<span class="time-box">{%s0}</span>
<span class="time-box ml">{%s1}</span>
<span class="time-text">秒</span>
</div>`,
};
},
onLoad(option) {
},
methods: {
callback() {
},
};
</script>
<style lang="scss" scoped>
.countdown-time-box {
display: flex;
// width: 60%;
.time-box {
color: #de4a2c;
font-size: 28rpx;
text-align: center;
background: #fff5de;
width: 38rpx;
height: 38rpx;
border-radius: 8rpx;
display: block;
line-height: 38rpx;
}
.ml {
margin-left: 8rpx;
}
.time-text {
margin: 0 12rpx;
}
}
</style>
日期转换为时间戳
let stemp = '2020-07-27 00:00:00';
let stime = new Date(stemp.replace(/-/g, '/')).getTime();