直接上代码,粘贴复制就可以用
<template>
<view class="qrcodebox">
<view class="tips" style="text-align: center;margin-bottom: 20rpx;">
请使用微信扫一扫进行扫码支付
</view>
<canvas id="qrcode" canvas-id="qrcode" style="width: 200px;height: 200px;margin: 0 auto;"></canvas>
<view style="text-align: center;margin-top: 30rpx;">剩余时间:{{ displayCountdown }}秒</view>
</view>
</template>
<script>
import UQRCode from '@/common/Sansnn-uQRCode/js_sdk/uqrcode/uqrcode.js';
import {
sv_notify
} from '@/api/yu/index.js'
export default {
data() {
return {
code_url: '',
countdowna: null, // 假设倒计时60秒
countdownb: null, // 假设倒计时60秒
timer: null, // 计时器
updateTimer: null,
paySn: '',
orderType: '',
displayCountdown: 60,
}
},
onShow() {
this.startCountdown();
this.startRequesting();
},
onLoad(e) {
console.log(e, 'e');
this.code_url = decodeURIComponent(e.code_url);
this.paySn = e.paySn
this.orderType = e.orderType
console.log(this.code_url, 'this.code_url');
this.getcodeurl()
},
beforeDestroy() {
// 离开页面时销毁定时器
clearInterval(this.timer);
clearInterval(this.updateTimer);
},
methods: {
getcodeurl() {
setTimeout(() => {
// 获取uQRCode实例
var qr = new UQRCode();
// 设置二维码内容
qr.data = this.code_url;
// 设置二维码大小,必须与canvas设置的宽高一致
qr.size = 200;
// 调用制作二维码方法
qr.make();
// 获取canvas上下文
var canvasContext = uni.createCanvasContext('qrcode', this); // 如果是组件,this必须传入
// 设置uQRCode实例的canvas上下文
qr.canvasContext = canvasContext;
// 调用绘制方法将二维码图案绘制到canvas上
qr.drawCanvas();
}, 1000)
},
startCountdown() {
this.countdowna = 60; // 设置倒计时初始值为60秒
this.countdownb = 60
// 每隔1秒更新页面显示的倒计时
this.updateTimer = setInterval(() => {
this.countdowna -= 1;
// 更新页面显示的倒计时
// 这里假设你有一个用于显示倒计时的变量,比如 this.displayCountdown
this.displayCountdown = this.countdowna;
if (this.countdowna <= 0) {
this.stopCountdown();
}
console.log(this.displayCountdown);
}, 1000);
console.log(this.updateTimer,'this.updateTimer');
// 每隔2秒执行一次操作
this.timer = setInterval(() => {
this.countdownb -= 2; // 每次减少2秒
let data = {
agentArea: uni.getStorageSync('Area'),
key: uni.getStorageSync('key'),
paySn: this.paySn,
orderType: this.orderType
}
sv_notify(data).then(res => {
console.log(res);
if (res.data.datas.is_pay == true) {
uni.showToast({
title: '支付成功',
icon: 'success',
duration: 2000
})
clearInterval(this.timer);
clearInterval(this.updateTimer);
setTimeout(() => {
uni.navigateTo({
url: '/pageA/wlcct/unexpired'
})
}, 2000)
}
})
if (this.countdownb <= 0) {
this.stopCountdown();
}
}, 2000);
console.log(this.timer,'this.timer');
},
stopCountdown() {
if (this.updateTimer) {
clearInterval(this.updateTimer);
this.updateTimer = null;
}
if (this.timer) {
clearInterval(this.timer);
this.timer = null;
uni.showToast({
title: '支付超时',
icon: 'success',
duration: 2000
});
setTimeout(() => {
uni.switchTab({
url: '/pages/wlcct/wlcct'
});
}, 2000);
}
},
}
}
</script>
<style>
</style>
注意在离开页面时倒计时未结束时需要注销计时器,不然会在其他页面继续执行倒计时
注销倒计时代码
beforeDestroy() {
// 离开页面时销毁定时器
clearInterval(this.timer);
clearInterval(this.updateTimer);
},
最终实现效果: