需求:客户在点击支付但未付款时,会生成待支付订单,待支付订单超过24小时,自动取消,须在订单列表界面显示倒计时
const awaitPay = new Map();
export default{
created() {
// 获取订单列表数据
this.init();
},
async init() {
// 格式化查询参数 (忽略)
this.initQuery();
// 获取数据
const res = await getList(this.searchForm);
if(res?.code === 200){
this.tableList = res.data; // 列表数据
this.searchForm.total = res.totalSize;
// 数据不为空
if (Array.isArray(this.tableList) && this.tableList.length) {
// 遍历订单数据
this.tableList.forEach((item) => {
// 存在待支付订单,执行倒计时处理
if (item.state === 1) {
// 创建时间 订单编号
this.deadLine(item.createTime, item.orderNo);
}
});
}
}
},
// 每秒执行一次
deadLine(createTime, id) {
const that = this;
const startTime = new Date(createTime).getTime() || null; // 将日期时间转成时间戳(毫秒)
const endTime = (startTime && startTime + 24 * 60 * 60 * 1000) || null; // 结束时间(+24h)
const timer = setInterval(() => {
const nowTime = Date.parse(new Date()); // 当前时间时间
const timeDiffer = endTime - nowTime; // 时间差 结束时间减去当前时间
const downTime =
endTime - nowTime >= 0 ? (endTime - nowTime) / 1000 : 0; // 距离到期所剩时间(转成秒)
const tem = {
timer,
downTime
};
awaitPay.set(id, tem);
that.countTime(downTime, id);
}, 1000);
},
// 超时24h的订单改为已取消
async countTime(downTime, id) {
const that = this;
const tem = awaitPay.get(id);
if (downTime <= 0) {
clearInterval(tem.timer);
that.timeObj = {};
// 超时 事件处理(后台自动把订单改为已取消)
await that.init();
} else {
tem.downTime--;
const min = Math.floor(tem.downTime % 3600);
const val =
// 一位数前面进行补0操作
that.$formatBit(Math.floor(tem.downTime / 3600)) +
':' +
that.$formatBit(Math.floor(min / 60)) +
':' +
that.$formatBit(tem.downTime % 60);
this.$nextTick(async() => {
this.$set(that.timeObj, id, val);
});
}
},
}
<el-table
:data="tableList"
:header-cell-style="_tableHeadStyle"
class="table-container"
@selection-change="onSelectionChange"
>
<el-table-column type="selection" align="center" width="60px" />
<el-table-column label="订单状态" prop="state" align="center">
<template slot-scope="scope">
<div v-if="scope.row.state == 1" style="color: #f10215">
<span>{{ maps._orderStateMap.get(scope.row.state) }}</span>
<br>
<!-- 显示倒计时 -->
<span style="color: #f10215">{{ timeObj[scope.row.orderNo] }}</span>
</div>
<span v-else>
{{
scope.row.state ? maps._orderStateMap.get(scope.row.state) : "--"
}}
</span>
</template>
</el-table-column>