vue.js

关注公众号 jb51net

关闭
首页 > 网络编程 > JavaScript > javascript类库 > vue.js > Vue PC前端扫码登录

Vue PC前端扫码登录功能实现

作者:前端碎碎念

最近在做APP客户端扫描PC端二维码登录,于是记录一下实现过程,下面这篇文章主要给大家介绍了关于Vue PC前端扫码登录功能实现的相关资料,文中通过实例代码介绍的非常详细,需要的朋友可以参考下

需求描述

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

思路解析

PC 扫码原理?

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

前端功能实现

如何生成二维码图片?

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.qsCodeTimer)
            this.qsCodeTimer = null
            return
          }
          this.effectiveTime--
        }, 1000)
      }

    },
   
    // 刷新二维码
    refreshCode() {
      this.codeStatus = 1
      this.effectiveTime = 30
      this.qsCodeTimer = null
      this.generateORCode()
    }
  },

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

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

使用长轮询实现:

 // 获取后台状态
    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.qsCodeTimer)
              this.qsCodeTimer = null
              this.effectiveTime = 0
            break;
            case 2:
              console.log("扫码通过")
              clearInterval(this.qsCodeTimer)
              this.qsCodeTimer = null
              this.$emit("login", loginData)
            break;
            case 1:
              console.log("未扫码")
              this.effectiveTime > 0  && this.checkQRcodeStatus()
            break;
            default:
            break;
         }
       } 
    },

参考资料:

总结

到此这篇关于Vue PC前端扫码登录功能实现的文章就介绍到这了,更多相关Vue PC前端扫码登录内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文