功能介紹 ,數組項有一個下單時間 ,比如今天下單在72小時內可以繼續支付,超過則默認取消訂單
- 頁面按鈕處 加上倒計時
<!-- 倒計時 -->
<text v-if="item.timeLeft > 0">{{ formatTime(item.remaining) }}</text>
- 邏輯處理
// 第一步 處理接口返回的數據 原本是沒有倒計時 remaining這個值的 我們根據狀態給數組項加上
const listData = ref([])
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;// 第三步 更新所有倒計時 這里的listData是頁面渲染的數組
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);
});