场景需求:
- PC端点击授权按钮弹框提示立即绑定公众号
- 生成二维码提供微信扫码授权
- PC端提示授权结果提示、微信公众号提示授权成功提示
解决方案:
- 利用
qrcodejs2插件
生成二维码(有容错率区别) - 需要实时调取接口返回授权绑定公众号是否成功
setInterval
定时器异步请求的回调反馈问题无法获取(利用Promise函数
)
插件引入使用方法可点击查看以往博客 点击这里
1、view层
<el-dialog
title="绑定公众号"
:visible.sync="authDialog"
width="60%">
<div class="tc">
<p class="mb10">这为保证所有功能的正常使用,授权时请把所有权限统一授权给惠联生花</p>
<el-button class="mt15" type="primary" @click="confirmBind()">立即绑定</el-button>
</div>
<el-dialog
width="30%"
title="扫码绑定"
:visible.sync="QRVisible"
:close-on-click-modal="false"
@close="qrClose"
append-to-body>
<div ref="qrBox" class="qrBox tc"></div>
</el-dialog>
</el-dialog>
2、methods层
关键点:
- qrcodejs2生成二维码时的容错率属性,PC端会导致扫码失败或扫不出
(correctLevel: QRCode.CorrectLevel.L //容错率,L/M/H)
- 只通过
setInterval异步函数
请求接口返回无法正常所需要的回调函数结果- 利用
Promise函数
中的resolve、reject返回请求结果处理回调函数逻辑- 处理结果后清除setInterval定时器、以及交互时清除
// 二维码关闭回调
qrClose(){
this.$refs.qrBox.innerHTML = ''
clearInterval(this.requestTimer);
},
// 绑定公众号
confirmBind(){
// 二维码URL
getCodeUrl(this.seller_id).then( res => {
this.qrUrl = res.data.url;
this.QRVisible = true;
this.$nextTick(()=>{
this.crateQrcode()
})
// 请求绑定返回(1分钟内)
let time = 60;
this.requestTimer = setInterval(() => {
if(time>0){
time--;
new Promise((resolve,reject) => {
// 授权结果返回接口
this.seller_id = getSellerId();
getBindResult(this.seller_id)
.then((res) => {
resolve(res)
})
.catch((res) => {
reject(res)
})
}).then( res => {
if(res.data == true){
this.$notify({
title: '成功',
message: '公众号绑定成功!',
type: 'success',
duration: 4000
});
this.QRVisible = false;
this.authDialog = false;
this.getHomeToday();
}
}).catch( res => {
this.$notify({
title: '失败',
message: '公众号绑定失败,请重新绑定!',
type: 'error',
duration: 4000
});
this.QRVisible = false;
this.authDialog = true;
})
}else{
clearInterval(this.requestTimer);
this.$notify({
title: '失败',
message: '公众号绑定失败,请重新绑定!',
type: 'error',
duration: 4000
});
this.QRVisible = false;
this.authDialog = true;
}
},6000)
}).catch(() => {
clearInterval(this.requestTimer);
})
},
crateQrcode(){
let qrcode = new QRCode(this.$refs.qrBox, {
text: this.qrUrl,
width: 120,
height: 120,
colorDark: '#000',
colorLight: '#fff',
correctLevel: QRCode.CorrectLevel.L //容错率,L/M/H
})
}
3、效果图: