1.新建组件cus-countdown.vue
<template>
<view class="w-100 cus-flex-center">
<!-- 天 -->
<view>
<view class="time__custom" v-if="days<10"><text>0</text>{{days}}</view>
<view class="time__custom" v-else>{{days}}</view>
</view>
<view class="text-xxs text-white" style="margin: 0 2px;">天</view>
<!-- 时 -->
<view>
<view class="time__custom" v-if="hours<10"><text>0</text>{{hours}}</view>
<view class="time__custom" v-else>{{hours}}</view>
</view>
<view class="text-xxs text-white" style="margin: 0 2px;">:</view>
<!-- 分 -->
<view>
<view class="time__custom" v-if="minutes<10"><text>0</text>{{minutes}}</view>
<view class="time__custom" v-else>{{minutes}}</view>
</view>
<view class="text-xxs text-white" style="margin: 0 2px;">:</view>
<!-- 秒 -->
<view>
<view class="time__custom" v-if="seconds<10"><text>0</text>{{seconds}}</view>
<view class="time__custom" v-else>{{seconds}}</view>
</view>
</view>
</template>
<script>
export default {
props: {
targetDate: {
type: Number,
required: true
}
},
data() {
return {
countdownInterval: null,
days: 0,
hours: 0,
minutes: 0,
seconds: 0
};
},
mounted() {
this.startCountdown();
},
beforeDestroy() {
clearInterval(this.countdownInterval);
},
methods: {
startCountdown() {
this.updateCountdown(); // 先立即更新一次
this.countdownInterval = setInterval(() => {
this.updateCountdown();
}, 1000);
},
updateCountdown() {
const now = new Date().getTime();
const target = this.targetDate * 1000;
const diff = Math.max(target - now, 0);
this.days = Math.floor(diff / (1000 * 60 * 60 * 24)); // 天数
this.hours = Math.floor((diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)); // 小时数
this.minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60)); // 分钟数
this.seconds = Math.floor((diff % (1000 * 60)) / 1000); // 秒数
if (diff <= 0) {
clearInterval(this.countdownInterval);
this.$emit('countdownFinished'); // 触发倒计时结束事件
}
}
}
};
</script>
<style lang="scss">
.time__custom {
width: 30rpx;
height: 30rpx;
background: #FFFFFF;
border-radius: 10rpx;
display: flex;
justify-content: center;
align-items: center;
font-size: 20rpx;
color: #FF4E76;
text-align: center;
}
</style>
2.页面调用组件
<view v-for="(item,index) in list" :key="index">
<!-- deadline:结束时间戳 如1724774400-->
<cusCountDown :targetDate="item.deadline" @countdownFinished="onCountdownFinished(index)" />
</view>
<script>
import cusCountDown from '@/components/cus-countdown/cus-countdown';
export default {
components: {
cusCountDown
},
data() {
return {
list:[]
}
},
methods: {
onCountdownFinished(e) {
console.log('倒计时结束')
},
}
}
<script>