效果图
<template>
<view class="countdown">
<view class="txt-time">{{ txtTime?.hou }}</view>:
<view class="txt-time">{{ txtTime?.min }}</view>:
<view class="txt-time">{{ txtTime?.sec }}</view>
</view>
</template>
<script lang="ts" setup>
import { onLoad, onHide } from '@dcloudio/uni-app';
import { computed } from 'vue';
import { ref } from 'vue';
const props = defineProps({
//时间搓
endTime: {
type: Number,
default: true
},
// 尺寸
size: {
type: Number,
default: 64
},
// 数字颜色
color: {
type: String,
default: "#F92834"
},
// 背景颜色
backgroundColor: {
type: String,
default: "#FFFFFF"
},
// 分号颜色
semicolon: {
type: String,
default: "#FFFFFF"
},
});
//尺寸
const mainSize = computed(() => {
return props.size + 'rpx'
})
//字体大小
const fontSize = computed(() => {
return props.size * (28 / 64) + 4 + 'rpx'
})
//时间文本
let txtTime = ref()
//计时器
let timeIntervalSingle = ref()
const singleCountDown = function () {
let time = 0;
let currentTime = new Date().getTime();//当前时间时间戳
time = (props.endTime - currentTime) / 1000;
// 如果活动未结束
if (time > 0) {
let hou = Math.floor(time / (60 * 60));
let min = Math.floor(time % (60 * 60 * 24) % 3600 / 60);
let sec = Math.floor(time % (60 * 60 * 24) % 3600 % 60);
txtTime.value = {
hou: timeFormat(hou),
min: timeFormat(min),
sec: timeFormat(sec)
}
} else { //活动已结束
txtTime.value = {
hou: "00",
min: "00",
sec: "00"
}
clearTimeout(timeIntervalSingle.value); //关闭定时器
}
timeIntervalSingle.value = setTimeout(singleCountDown, 1000);
}
//时间补零
const timeFormat = (param: number) => {
return param < 10 ? '0' + param : param;
}
//页面加载时就启动定时器
onLoad(() => {
singleCountDown();
})
//页面切换时就关闭定时器
onHide(() => {
timeIntervalSingle.value = setTimeout(singleCountDown, 1000);
})
</script>
<style lang="scss" scoped>
.countdown {
display: flex;
justify-content: center;
align-items: center;
color: v-bind(semicolon);
.txt-time {
font-size: v-bind(fontSize);
color: v-bind(color);
background-color: v-bind(backgroundColor);
border-radius: 10rpx;
margin: 0 4rpx;
font-weight: bold;
height: v-bind(mainSize);
width: v-bind(mainSize);
line-height: v-bind(mainSize);
text-align: center;
}
}
</style>
<HagglingCountdown :endTime="时间搓毫秒" />