vue项目引用QRCode生成二维码扫码实现app登录
效果如下
1、安装
npm install --save qrcode
2、template
<template>
<div class="login-content_code">
<h1>打开XXAPP扫描二维码登录</h1>
<div class="qr-code-area">
<img class="login-qr-code" :src='qrCodeData.loginQrCode'> // 放置二维码的地方
<div class="cover" v-if="qrCodeData.loginQRCodeStatus != 'normal'"> // 二维码登录状态不正常时
<div
v-if="qrCodeData.loginQRCodeStatus == 'timeout'" // 二维码超时
style="color:#333333;cursor:pointer"
@click="handle_refreshLoginQrCode"
>
二维码已过期
<br>
请点击刷新
</div>
</div>
</div>
</div>
</template>
2、step函数中
import QRCode from 'qrcode'
const qrCodeData = reactive({
loginQRCodeStatus: 'notGet', // 二维码登录状态 | normal 正常 | timeout 超时 | success 登录成功
qrToken: "",
loginQrCode: "", // 二维码图片
loginQrCodeTimer: 0, // 有效时间
checkLoginTimer: 0, // 轮询时间
})
onMounted(()=>{
getLoginQrCode()
}) // 初始二维码
async function getLoginQrCode() {
let res = await axios.post({
.....
}) // 获取app扫码登录的二维码标识
qrCodeData.qrToken = res.data // 将返回的data里的字符串生成二维码
QRCode.toDataURL(JSON.stringify({
content: qrCodeData.qrToken,
copyright: "app",
function: "pc_login",
time: new Date().getTime()
}))
.then(url => {
qrCodeData.loginQrCode = url // 生成的二维码
})
.catch(err => {
console.error(err)
})
qrCodeData.loginQRCodeStatus = 'normal' // 将状态设置为正常
qrCodeData.loginQrCodeTimer = setTimeout(() => {
qrCodeData.loginQRCodeStatus = 'timeout'
clearInterval(qrCodeData.loginQrCodeTimer)
}, 1000 * 60 * 5) // 有效期5分钟
checkAppLogin()
}
function checkAppLogin () {
if ( qrCodeData.loginQRCodeStatus === 'normal') {
// 开启检测
qrCodeData.checkLoginTimer = setTimeout(async () => { // 轮询
// 发起扫app二维码登录的接口
let res = axios.post({
......
})
....// 根据返回的状态做相应的操作
if (res.code === 211) {
// 二维码已过期,请刷新
qrCodeData.loginQRCodeStatus = 'timeout'
return
}
if (res.code === 210) {
// 继续检查是否被使用
checkAppLogin()
return
}
if (res.code === 200) {
// 登录成功
afterLogin(res)
return
}
....
clearInterval(qrCodeData.checkLoginTimer)
}, 1000)
}
else {
clearInterval(qrCodeData.checkLoginTimer)
}
}
function handle_refreshLoginQrCode () {
getLoginQrCode()
}
function afterLogin() {
..... // 登录成功后操作
}