这里给大家分享我在网上总结出来的一些知识,希望对大家有所帮助

记录--Vue PC前端扫码登录

记录--Vue PC前端扫码登录

需求描述

目前大多数PC端应用都有配套的移动端APP,如微信,淘宝等,通过使用手机APP上的扫一扫功能去扫页面二维码图片进行登录,使得用户登录操作更方便,安全,快捷。

思路解析

PC 扫码原理?

扫码登录功能涉及到网页端、服务器和手机端,三端之间交互大致步骤如下:

  1. 网页端展示二维码,同时不断的向服务端发送请求询问该二维码的状态;
  2. 手机端扫描二维码,读取二维码成功后,跳转至确认登录页,若用户确认登录,则服务器修改二维码状态,并返回用户登录信息;
  3. 网页端收到服务器端二维码状态改变,则跳转登录后页面;
  4. 若超过一定时间用户未操作,网页端二维码失效,需要重新刷新生成新的二维码。

前端功能实现

如何生成二维码图片?

  • 二维码内容是一段字符串,可以使用uuid 作为二维码的唯一标识;
  • 使用qrcode插件 import QRCode from 'qrcode'; 把uuid变为二维码展示给用户
import {v4 as uuidv4} from "uuid"
import QRCode from "qrcodejs2"
let timeStamp = new Date().getTime() // 生成时间戳,用于后台校验有效期
let uuid = uuidv4()
let content = `uid=${uid}&timeStamp=${timeStamp}`
this.$nextTick(()=> {
const qrcode = new QRCode(this.$refs.qrcode, {
text: content,
width: 180,
height: 180,
colorDark: "#333333",
colorlight: "#ffffff",
correctLevel: QRCode.correctLevel.H,
render: "canvas"
})
qrcode._el.title = ''

如何控制二维码的时效性?

使用前端计时器setInterval, 初始化有效时间effectiveTime, 倒计时失效后重新刷新二维码

export default {
name: "qrCode",
data() {
return {
codeStatus: 1, // 1- 未扫码 2-扫码通过 3-过期
effectiveTime: 30, // 有效时间
qrCodeTimer: null // 有效时长计时器
uid: '',
time: ''
};
},
methods: {
// 轮询获取二维码状态
getQcodeStatus() {
if(!this.qsCodeTimer) {
this.qrCodeTimer = setInterval(()=> {
// 二维码过期
if(this.effectiveTime <=0) {
this.codeStatus = 3
clearInterval(this.qrCodeTimer)
this.qrCodeTimer = null
return
}
this.effectiveTime--
}, 1000)
}
},
// 刷新二维码
refreshCode() {
this.codeStatus = 1
this.effectiveTime = 30
this.qrCodeTimer = null
this.generateORCode()
}
},

前端如何获取服务器二维码的状态?

前端向服务端发送二维码状态查询请求,通常使用轮询的方式

  • 定时轮询:间隔1s 或特定时段发送请求,通过调用setInterval(), clearInterval()来停止;
  • 长轮询:前端判断接收到的返回结果,若二维码仍未被扫描,则会继续发送查询请求,直至状态发生变化(失效或扫码成功)
  • Websocket:前端在生成二维码后,会与后端建立连接,一旦后端发现二维码状态变化,可直接通过建立的连接主动推送信息给前端。

使用长轮询实现:

 // 获取后台状态
async checkQRcodeStatus() {
const res = await checkQRcode({
uid: this.uid,
time: this.time
})
if(res && res.code == 200) {
let codeStatus - res.codeStatus
this.codeStatus =  codeStatus
let loginData = res.loginData
switch(codeStatus) {
case 3:
console.log("二维码过期")
clearInterval(this.qrCodeTimer)
this.qrCodeTimer = null
this.effectiveTime = 0
break;
case 2:
console.log("扫码通过")
clearInterval(this.qrCodeTimer)
this.qrCodeTimer = null
this.$emit("login", loginData)
break;
case 1:
console.log("未扫码")
this.effectiveTime > 0  && this.checkQRcodeStatus()
break;
default:
break;
}
}
},

本文转载于:

https://juejin.cn/post/7179821690686275621

如果对您有所帮助,欢迎您点个关注,我会定时更新技术文档,大家一起讨论学习,一起进步。

记录--Vue PC前端扫码登录

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。