<div class="qrcodeCanvas">
<div id="qrcode" v-loading="expireLoading"></div>
<div class="markQr" v-if="expireSign" @click="getCode">
<i class="iconfont icon-tuzhishuchu-xiazaichajianshuaxin"></i>
</div>
</div>
<p class="bottomText">{{expireSign?'点击重新获取':'请用XXX扫描二维码登录'}}</p>
data参数:
qrcode: null,
qrCodeStr: "",
getInfoCode: "",
expireSign: false, // 是否展示二维码蒙版层
expireLoading: false, // 控制loading状态
methods方法:
// 首先在用户选择切换到二维码扫码页面时,获取后台传递的二维码地址
getCode() {
this.expireLoading = true; this.expireSign = false;
// 向后台发送请求获取code
.get("/xx/xx/xx)
.then(res => {
this.qrCodeStr = res.qrCode; // 二维码code this.getInfoCode = res.code; // 登录的code码
this.createQrcode(res.qrCode); // 1. *创建一个二维码*
this.checkLogin(); // *2. 检查登录状态,单点 模拟form表单登录重定向*
})
.catch(() => {
this.expireLoading = false; this.expireSign = true;
this.$message({ type: "error", message: "获取二维码失败!" });
});
},
使用qrcodejs2生成二维码
步骤:
1. 安装:cnpm i qrcodejs2 -S
2. 引入: import QRCode from "qrcodejs2";
3. 使用:
// 创造二维码
createQrcode(str) {
if (this.qrcode) {
this.qrcode.clear(); // clear the code.
this.qrcode.makeCode(str);
} else {
this.qrcode = new QRCode("qrcode", {
width: 152,
height: 152,
text: str // 二维码地址
});
}
this.expireLoading = false;
this.expireSign = false;
},
/**
* 扫码登录,轮询登录结果
*/
checkLogin() {
let that = this;
this.timer1 = setInterval(() => {
if (that.getInfoCode) {
that.$axios
.get("/auth/qrcode/check?code=" + that.getInfoCode)
.then(res => {
if (res.body.countDown == 1) {
that.$message({
type: "warning",
message: "二维码失效,请重新扫描!"
});
that.expireSign = true;
that.expireLoading = false;
window.clearInterval(that.timer1);
} else {
if (res.body.status == "1") {
that.expireLoading = true;
}
if (res.body.status == "2") {
// status为2,代表二维码登录成功,清除轮询
window.clearInterval(that.timer1);
// 进行登录准备
this.beforeCodeSubmit()
// that.expireLoading = false;
}
}
})
.catch(() => {
that.expireLoading = false;
that.expireSign = true;
that.$message({ type: "error", message: "登录失败!" });
window.clearInterval(that.timer1);
});
}
}, 3000);
},
//code登录准备
beforeCodeSubmit() {
// 参数
const route = this.$route;
const query = route.query || {};
//登录成功后的回跳地址
const redirect_uri = query.redirect_uri && decodeURIComponent(query.redirect_uri) || location.origin;
const data = {
grant_type: 'qrcode',
code: this.getInfoCode,
client_id: 'portal',
response_type: 'code',
redirect_uri,
login_page: location.origin + '/#/login',
}
this.codeSubmit(data)
},
//code模拟form登录框,只有用原生form表单提交才可以重定向
codeSubmit(data){
const $form = document.createElement('form');
$form.setAttribute('action', this.$config.baseURL + '/auth/oauth/appqr/code');
$form.setAttribute('method','post');
for(let key in data){
const $el = document.createElement('input');
$el.setAttribute('name',key);
$el.value = data[key];
$form.appendChild($el);
}
document.documentElement.appendChild($form);
$form.submit();
},
效果: