search
HomeWeb Front-endVue.jsDetailed explanation of how to implement the QR code login function on the Vue PC side

This article brings you relevant knowledge about Vue. It mainly introduces the principle of implementing code scanning on the PC side? How to generate a QR code image? How to use Vue to implement front-end QR code login? For those who are interested, let’s take a look below. I hope it will be helpful to everyone.

Requirement Description

Currently, most PC applications have supporting mobile APPs, such as WeChat, Taobao, etc. By using the scan on the mobile APP The scan function is used to scan the QR code image on the page to log in, making the user login operation more convenient, safe and fast.

Idea Analysis

Principle of PC scanning code?

The scan code login function involves the web page, the server and the mobile phone. The general steps of interaction between the three ends are as follows:

  • The web page displays the QR code and continuously Send a request to the server to inquire about the status of the QR code;

  • The mobile phone scans the QR code. After successfully reading the QR code, it jumps to the confirmation login page. If the user After confirming the login, the server will modify the QR code status and return the user login information;

  • The web page will jump to the post-login page after receiving the server-side QR code status change;

  • If the user does not operate for a certain period of time, the QR code on the web page will become invalid, and a new QR code needs to be refreshed and generated.

Front-end function implementation

How to generate a QR code image?

  • The content of the QR code is a string, you can use uuid as the unique identifier of the QR code;
  • Use the qrcode plug-in import QRCode from 'qrcode'; to change the uuid into two The QR code is displayed to the user
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 = ''

How to control the timeliness of the QR code?

Use the front-end timer setInterval, initialize the effective time effectiveTime, and refresh the QR code after the countdown expires

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()
    }
  },

How does the front-end obtain the status of the server QR code?

The front end sends a QR code status query request to the server, usually using polling

  • 定时轮询:间隔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.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.js视频教程

The above is the detailed content of Detailed explanation of how to implement the QR code login function on the Vue PC side. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:juejin. If there is any infringement, please contact admin@php.cn delete
Vue.js and React: Understanding the Key DifferencesVue.js and React: Understanding the Key DifferencesApr 10, 2025 am 09:26 AM

Vue.js is suitable for small to medium-sized projects, while React is more suitable for large and complex applications. 1. Vue.js' responsive system automatically updates the DOM through dependency tracking, making it easy to manage data changes. 2.React adopts a one-way data flow, and data flows from the parent component to the child component, providing a clear data flow and an easy-to-debug structure.

Vue.js vs. React: Project-Specific ConsiderationsVue.js vs. React: Project-Specific ConsiderationsApr 09, 2025 am 12:01 AM

Vue.js is suitable for small and medium-sized projects and fast iterations, while React is suitable for large and complex applications. 1) Vue.js is easy to use and is suitable for situations where the team is insufficient or the project scale is small. 2) React has a richer ecosystem and is suitable for projects with high performance and complex functional needs.

How to jump a tag to vueHow to jump a tag to vueApr 08, 2025 am 09:24 AM

The methods to implement the jump of a tag in Vue include: using the a tag in the HTML template to specify the href attribute. Use the router-link component of Vue routing. Use this.$router.push() method in JavaScript. Parameters can be passed through the query parameter and routes are configured in the router options for dynamic jumps.

How to implement component jump for vueHow to implement component jump for vueApr 08, 2025 am 09:21 AM

There are the following methods to implement component jump in Vue: use router-link and <router-view> components to perform hyperlink jump, and specify the :to attribute as the target path. Use the <router-view> component directly to display the currently routed rendered components. Use the router.push() and router.replace() methods for programmatic navigation. The former saves history and the latter replaces the current route without leaving records.

How to jump to the div of vueHow to jump to the div of vueApr 08, 2025 am 09:18 AM

There are two ways to jump div elements in Vue: use Vue Router and add router-link component. Add the @click event listener and call this.$router.push() method to jump.

How to transfer value by jumping vueHow to transfer value by jumping vueApr 08, 2025 am 09:15 AM

There are two main ways to pass data in Vue: props: one-way data binding, passing data from the parent component to the child component. Events: Pass data between components using events and custom events.

How to jump to the introduction method of vueHow to jump to the introduction method of vueApr 08, 2025 am 09:12 AM

Vue.js provides three ways to jump: native JavaScript API: use window.location.href to jump. Vue Router: Use the <router-link> tag or this.$router.push() method to jump. VueX: Trigger route jump through dispatch action or commit mutation.

How to set up a jump page for vueHow to set up a jump page for vueApr 08, 2025 am 09:09 AM

There are several ways to set up page redirects in Vue, including creating clickable links using the router-link component. Use the router.push() method to manually add new routes to the history stack. Use the router.replace() method to replace the current route. Redirect to a new page directly using location.href.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use