2023/09/03

Vue.js 3 掃描QR Code

公司剛好有網頁項目需要透過QR Code掃描,所以我就選了Html5-QRCode這個套件來解決QR Code或之後其他掃描代碼的解決方案

要注意的是Vue會再mounted渲染模板上去,所以別再created時去呼叫DOM



<template>
  <div id="reader"></div>
</template>

<script>
import {Html5Qrcode, Html5QrcodeScanType, Html5QrcodeSupportedFormats} from "html5-qrcode"

export default {
  data() {
    return {
      scanner: null,
    }
  },
  methods: {
    /**
     * Close QRCode
     */
    close() {
      if (this.scanner) {
        this.scanner.stop()
      }
    },
    /**
     * Open QRCode
     */
    open() {
      this.scanner = new Html5Qrcode("reader")
      this.scanner.start(this.selectDevice, {
          formatsToSupport: [
            Html5QrcodeSupportedFormats.QR_CODE,
          ],
          supportedScanTypes: [
            Html5QrcodeScanType.SCAN_TYPE_CAMERA
          ],
          fps: 10,
          aspectRatio: 1.777778,
          qrbox: {
            width: 250,
            height: 250
          },
        },
        (decodedText, decodedResult) => {
          this.stop()
        },
        (errorMessage, error) => {
        }
      )
    }
  },
  mounted() {
    this.open()
  }
}
</script>