uni-app实现订单支付倒计时,不会随着返回重新计时
uni-app实现订单支付倒计时
最近开发时有一个倒计时功能,一开始使用uni-app中自带的uni-countdown倒计时,可以实现普通倒计时,但是并不能满足需求根据订单支付时间倒计时10分钟,每次刷新会重新计时,为了解决这个问题我尝试将获得的支付时间传入,取支付后的第十分钟作为截止时间。
获取下单时间
template中写好一个定时器:
<uni-countdown v-if="item.orderStatu == 1" class="room-count" color="#FF5733" :show-day="false" :second="timeupSecond" @timeup="timeup(item.createTime)" />
<text v-if="item.orderStatu == 1" class="room-count-txt">之后取消</text>
item.orderStatu == 1是待支付的状态,:show-day="false"表示不显示天数,timeupSecond是被绑定的时间值。
特别注意初始化timeupSecond时必须:
timeupSecond:null,
定时器方法
// 倒计时
timeup(createTime) {
var that = this;
/**setInterval间歇调用 */
that.timer = setInterval(function () {
//订单下单时间
var buy_time = createTime;
//计算剩余时间
var time = (new Date(buy_time).getTime() + 10* 60 * 1000) - (new Date().getTime());
if(time>0){
//计算剩余的分钟
var minutes = parseInt(time / 1000 / 60 % 60, 10);
//计算剩余的秒数
var seconds = parseInt(time / 1000 % 60, 10);
that.timeupSecond=parseInt(time / 1000);
// console.log(that.timeupSecond)
//判断分钟和秒数小于10要在前面加个0.
if(minutes<10){
minutes = '0' + minutes;
}
if (seconds < 10) {
seconds = '0' + seconds;
}
var timer = minutes + ":" + seconds;
}
}, 1000);
if(that.timeupSecond==0) {
uni.showToast({
title: '时间到'
})
this.getOrderPage()
}
},
timeup(createTime)里的createTime是从订单信息中获取的下单时间;
new Date(buy_time).getTime() + 10* 60 * 1000是设置倒计时的截止时间为下单10分钟后;
timeupSecond把时间转化成我需要的时间格式
如图为最终效果:
刷新或退出页面重新进入并不会重新倒计时,会一直到截止时间该倒计时样式会消失
这个方式确实会有多个订单的公用同一个timeupSecond的问题,会导致所有倒计时一样,解决方法是把timeupSecond加入订单数组中,push进订单数组,将timeupSecond变成该数组的item.timeupSecond。
uni-app实现订单支付倒计时(亲测可用)
使用uv-count-down组件
<view class="header_time" :style="{ paddingTop: statusBarH * 2 + 72 + 'rpx' }" v-if="info.orderStatus === '1'">
剩余
<uv-count-down v-if="info.countDownTime" :time="info.countDownTime" format="mm:ss" @finish="finish(info)"></uv-count-down>
</view>
info.orderStatus === '1’是待支付状态。
// 获取订单信息
async getData() {
const res = await this.$myRequest({
url: '/mhotel/ampgetBookingById.action',
data: {
bookingId: this.id
}
})
// console.log(res)
if (res.code === 200) {
this.info = res.data
// 计算出倒计时时间(毫秒)
let temLockTime = this.info.lockTime ? this.info.lockTime * 1 : 15
// 兼容ios部分系统转换时间格式
let createTime = this.info.createTime.slice(0, 19).replace(/-/g, '/')
this.info.countDownTime = new Date(createTime).getTime() + temLockTime * 60 * 1000 - new Date().getTime()
}
},
this.info.lockTime是后端给定的倒计时时间(分钟),如果后端没给定则默认15分钟;this.info.createTime是订单下单时间;
this.info.countDownTime是剩余支付时间。
最终倒计时结束回调:
// 倒计时结束回调
async finish(item) {
const res = await this.$myRequest({
url: '/mhotel/abkupdateOrderStatus.action',
data: {
bookingId: item.id
}
})
// console.log(res)
if (res.code === 200) {
item.orderStatus = '6'//倒计时结束都未付款订单状态改为取消
}
},