vue.js

关注公众号 jb51net

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

Vue PC端实现扫码登录功能示例代码

作者:忧郁的蛋~

目前大多数PC端应用都有配套的移动端APP,如微信,淘宝等,通过使用手机APP上的扫一扫功能去扫页面二维码图片进行登录,使得用户登录操作更方便,安全,快捷,这篇文章主要介绍了Vue PC端如何实现扫码登录功能,需要的朋友可以参考下

本篇文章给大家带来了关于Vue的相关知识,其中主要介绍了在PC端实现扫码的原理是什么?怎么生成二维码图片?怎么用Vue实现前端扫码登录?感兴趣的朋友,下面一起来看一下吧,希望对大家有帮助。

需求描述

目前大多数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端扫码登录内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

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