場景需求:
- 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;
new Promise((resolve,reject) => {
this.requestTimer = setInterval(() => {
this.seller_id = getSellerId();
if(time>0){
time--;
getBindResult(this.seller_id)
.then((res) => {
resolve(res)
})
.catch((res) => {
reject(res)
})
// console.log(time)
}else{
clearInterval(this.requestTimer);
this.$notify({
title: '失敗',
message: '公衆號綁定失敗,請重新綁定!',
type: 'error',
duration: 4000
});
this.QRVisible = false;
this.authDialog = true;
}
},6000)
}).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;
})
}).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、效果圖: