<template>
<view class="timer flex1">
<view>Remaining</view>
<view class="time flex1">{{formatNumber(days)}}</view>
<view>Day</view>
<view class="time flex1">{{formatNumber(hours)}}</view>
<view>:</view>
<view class="time flex1">{{formatNumber(minutes)}}</view>
<view>:</view>
<view class="time flex1">{{ formatNumber(seconds) }}</view>
</view>
</template>
<script setup>
import {
ref,
onMounted,
onUnmounted,
defineProps
} from 'vue'
const props = defineProps(['endTime']);
// 计算剩余秒数,起始时间为现在时间,结束时间为传入的 endTime
const count = ref(Math.floor((props.endTime - Math.floor(Date.now() / 1000)))); // 剩余秒数
const days = ref(Math.floor(count.value / (3600 * 24)))
const hours = ref(Math.floor((count.value % (3600 * 24)) / 3600))
const minutes = ref(Math.floor((count.value % 3600) / 60))
const seconds = ref(count.value % 60)
// 格式化数字,确保始终显示两位数
const formatNumber = (num) => {
return num < 10 ? `0${num}` : num
}
let timer;
const startCountDown = () => {
const update = () => {
count.value--
if (count.value <= 0) {
clearInterval(timer)
} else {
updateCountDown()
setTimeout(update, 1000)
}
}
const timer = setTimeout(update, 1000)
}
// 更新倒计时显示
const updateCountDown = () => {
days.value = Math.floor(count.value / (3600 * 24))
hours.value = Math.floor((count.value % (3600 * 24)) / 3600)
minutes.value = Math.floor((count.value % 3600) / 60)
seconds.value = count.value % 60
}
// 组件挂载时开始倒计时
onMounted(() => {
startCountDown()
})
// 组件销毁时清除定时器
onUnmounted(() => {
clearTimeout(timer)
})
</script>
<style lang="scss">
.timer {
color: #71FA94;
text-align: center;
font-size: 12px;
.time {
color: #FFFFFF;
background-image: url("~@/static/images/ramadan/count_down_bg.png"); // 使用CSS变量作为背景图片
background-repeat: no-repeat;
background-size: cover;
height: 26px;
width: 35px;
margin: 0px 5px;
}
}
</style>