1. 程式人生 > 其它 >Vue掃描二維碼

Vue掃描二維碼

網頁實現掃描二維碼.

外掛:npm install --save vue-qrcode-reader

Tips:需要在https協議下才可以呼叫相機,實現掃碼。
  可以通過配置vue.config.js中的devServer:{https:true}

程式碼:

<template>
  <div>
    <p class="error">{{ error }}</p>
    <!--錯誤資訊-->

    <p class="decode-result">
      掃描結果: <b>{{ result }}</b>
    </p>
    <!--掃描結果-->
  
      <qrcode-stream @decode="
onDecode" @init="onInit" /> </div> </template> <script> //下載外掛 //cnpm install --save vue-qrcode-reader //引入 import { QrcodeStream } from 'vue-qrcode-reader'; export default { //註冊 components: { QrcodeStream }, data() { return { result: '',//掃碼結果資訊 error: '',//錯誤資訊
} }, methods: { onDecode(result) { alert(result); this.result = result }, async onInit(promise) { try { await promise } catch (error) { if (error.name === 'NotAllowedError') { this.error = "ERROR: 您需要授予相機訪問許可權" } else
if (error.name === 'NotFoundError') { this.error = "ERROR: 這個裝置上沒有攝像頭" } else if (error.name === 'NotSupportedError') { this.error = "ERROR: 所需的安全上下文(HTTPS、本地主機)" } else if (error.name === 'NotReadableError') { this.error = "ERROR: 相機被佔用" } else if (error.name === 'OverconstrainedError') { this.error = "ERROR: 安裝攝像頭不合適" } else if (error.name === 'StreamApiNotSupportedError') { this.error = "ERROR: 此瀏覽器不支援流API" } } } } } </script> <style scoped> .error { font-weight: bold; color: red; } </style>
Code