功能介绍 ,数组项有一个下单时间 ,比如今天下单在72小时内可以继续支付,超过则默认取消订单

- 页面按钮处 加上倒计时
html
<!-- 倒计时 -->
<text v-if="item.timeLeft > 0">{{ formatTime(item.remaining) }}</text>
- 逻辑处理
javascript
// 第一步 处理接口返回的数据 原本是没有倒计时 remaining这个值的 我们根据状态给数组项加上
console.log("列表数据", res);
res.forEach((item) => {
if (item.actions.pay) {
const createTime = new Date(item.create_time).getTime(); // 下单时间处理
item.endTime = createTime + 72 * 3600 * 1000; // 计算72小时截止时间
item.remaining = 0; // 剩余时间(毫秒)
item.timeLeft = true; // 倒计时状态
}
})
updateAllTimers();
// 第二步 统一定时器
let timer;
// 第三步 更新所有倒计时
const updateAllTimers = () => {
const now = Date.now();
listData.value.forEach(item => {
const diff = item.endTime - now;
item.remaining = diff;
item.timeLeft = diff > 0;
});
};
// 第四步 时间格式化函数
const formatTime = (milliseconds) => {
if (milliseconds <= 0) return '00:00:00';
const totalSeconds = Math.floor(milliseconds / 1000);
const hours = Math.floor(totalSeconds / 3600).toString().padStart(2, '0');
const minutes = Math.floor((totalSeconds % 3600) / 60).toString().padStart(2, '0');
const seconds = (totalSeconds % 60).toString().padStart(2, '0');
return `${hours}:${minutes}:${seconds}`;
};
// 生命周期管理
onMounted(() => {
timer = setInterval(updateAllTimers, 1000);
});
// 卸载
onUnmounted(() => {
clearInterval(timer);
});