Files
crm-uni/components/Countdown/time-counter.vue
T
2025-04-03 14:12:52 +08:00

114 lines
2.4 KiB
Vue

<template>
<view class="countdown">
<view class="time green">
<image src="/static/image/gtime.png" mode=""></image>
<text>{{ timeObj.days }}{{$t('day')}} </text>
<text> {{ timeObj.hours | padZero }} : </text>
<text> {{ timeObj.minutes | padZero }} : </text>
<text> {{ timeObj.seconds | padZero }}</text>
</view>
</view>
</template>
<script>
export default {
props: {
// 起始时间
totalSeconds: {
type: '',
required: true
},
// 是否显示天数
showDays: {
type: Boolean,
default: true
}
},
data() {
return {
startTime: this.totalSeconds, // 开始时间(Date对象)
elapsedTime: 0, // 已过时间(毫秒)
timer: null, // 计时器对象
isRunning: false, // 是否运行中
startTimeStr: '' ,// 显示用的开始时间字符串
timeObj: {
days: 0,
hours: 0,
minutes: 0,
seconds: 0
},
}
},
mounted() {
this.runCountdown();
},
filters: {
padZero(value) {
return value.toString().padStart(2, '0');
}
},
methods: {
// 计算已过时间
calculateElapsed() {
if (this.startTime) {
// 计算差值(毫秒)
let diff = this.startTime
const dateStr = diff;
const timestamp = new Date(dateStr).getTime();
// 处理iOS兼容性问题(推荐写法)
const iosFriendlyTimestamp = new Date(dateStr.replace(/-/g, '/')).getTime();
// 当前时间戳(毫秒)
const now = Date.now()
// 计算差值(毫秒)
let diff1 = Math.abs(now - iosFriendlyTimestamp)
// 计算各个单位
const seconds = Math.floor(diff1 / 1000)
this.timeObj.days = Math.floor(seconds / (24 * 3600));
const remaining = seconds % (24 * 3600);
this.timeObj.hours = Math.floor(remaining / 3600);
this.timeObj.minutes = Math.floor((remaining % 3600) / 60);
this.timeObj.seconds = remaining % 60;
}
},
runCountdown() {
if (!this.isRunning && this.startTime) {
this.isRunning = true
this.timer = setInterval(() => {
this.calculateElapsed()
}, 1000)
}
},
},
beforeDestroy() {
clearInterval(this.timer);
}
}
</script>
<style lang="scss">
.countdown {
.time {
display: flex;
align-items: center;
text {
margin: 0px 2px;
}
}
image {
width: 18px;
height: 18px;
margin-right: 5px;
}
}
.green {
color: #27C89C;
}
.timered {
color: #FF4040;
}
</style>