Files
xl-mobile/src/components/XCountdown.vue
2025-07-02 09:52:55 +08:00

65 lines
1.9 KiB
Vue

<script setup>
import {ref, watch} from "vue";
import dayjs from "dayjs";
const props = defineProps({
time: {
type: String,
default: null,
}
});
const diff = ref(dayjs(props.time).diff(dayjs(new Date()), 'second'));
const hours = ref(null);
const minutes = ref(null);
const seconds = ref(null);
let timer = null;
watch(
() => props.time,
() => {
console.log('运行')
clearInterval(timer);
diff.value = dayjs(props.time).diff(dayjs(new Date()), 'second');
hours.value = Math.floor(diff.value / 3600);
minutes.value = Math.floor((diff.value % 3600) / 60);
seconds.value = diff.value % 60;
timer = setInterval(() => {
diff.value = dayjs(props.time).diff(dayjs(new Date()), 'second');
hours.value = Math.floor(diff.value / 3600);
minutes.value = Math.floor((diff.value % 3600) / 60);
seconds.value = diff.value % 60;
}, 1000);
},
{deep: true, immediate: true}
)
</script>
<template>
<view class="!flex items-center gap-[20rpx]">
<slot></slot>
<view class="!flex gap-[16rpx] items-center">
<view class="time-block" v-if="hours && hours>0">{{ hours < 10 ? `0${hours}` : hours }}</view>
<view v-if="hours">:</view>
<view class="time-block" v-if="minutes && minutes>0">{{ minutes < 10 ? `0${minutes}` : minutes }}</view>
<view v-if="minutes">:</view>
<view class="time-block" v-if="seconds && seconds>0">{{ seconds < 10 ? `0${seconds}` : seconds }}</view>
</view>
</view>
</template>
<style lang="scss" scoped>
.time-block {
background-color: #E8F3FF;
border-radius: 4rpx;
padding: 4rpx;
color: rgb(22, 93, 255);
font-size: 24rpx;
font-weight: 500;
line-height: 140%;
letter-spacing: 0;
text-align: center;
}
</style>