第一步:样式实现
在 <style> 标签中添加以下样式代码:
.flash-sale-time {
display: flex;
align-items: center;
font-size: 14px;
}
.time-box {
display: flex;
align-items: center;
margin-left: 10px;
}
.day {
font-size: 16px;
color: #fff;
margin-right: 5px;
}
.time-box-item {
display: flex;
align-items: center;
background-color: #333;
color: #fff;
padding: 5px;
border-radius: 3px;
margin-right: 5px;
}
.time-box-item-num {
font-size: 16px;
margin: 0 2px;
}
第二步:逻辑实现
添加一个倒计时逻辑。可以在 <script> 标签中添加以下代码:
<script>
export default {
data() {
return {
countdown: {
days: '02',
hours: '08',
minutes: '32',
seconds: '59'
}
};
},
created() {
this.startCountdown();
},
methods: {
startCountdown() {
const targetTime = new Date('2025-01-05T00:00:00+08:00').getTime();
const updateCountdown = () => {
const now = new Date('2025-01-03T16:19:14+08:00').getTime();
const distance = targetTime - now;
if (distance > 0) {
this.countdown.days = Math.floor(distance / (1000 * 60 * 60 * 24)).toString().padStart(2, '0');
this.countdown.hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)).toString().padStart(2, '0');
this.countdown.minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60)).toString().padStart(2, '0');
this.countdown.seconds = Math.floor((distance % (1000 * 60)) / 1000).toString().padStart(2, '0');
}
};
updateCountdown();
setInterval(updateCountdown, 1000);
}
}
};
</script>
第三步:更新模板
在模板中,我们需要使用数据绑定来显示倒计时:
<view class="right flash-sale-time">
<text class="flash-sale-tit">
距离结束还剩
</text>
<view class="time-box">
<view class="day">{{ countdown.days }}天</view>
<view class="time-box-item">
<text class="time-box-item-num">{{ countdown.hours }}</text>:
<text class="time-box-item-num">{{ countdown.minutes }}</text>:
<text class="time-box-item-num">{{ countdown.seconds }}</text>
</view>
</view>
</view>