h5页面扫码生成取货码实现功能

244 阅读1分钟

页面效果:

1718768817699.png

1718769001548.png

1718769936606.png

html:

<el-form-item label="取货码" class="pickupCode">
    <el-input v-model="data.form.code" :disabled="data.isPickupCode"/>
    <el-icon class="cameraFilled" size="20" @click="openQrcode" v-if="!data.isPickupCode">
    <img src="@/assets/sao.png" alt=""></el-icon>
</el-form-item>

<div class="scanCode" v-if="isQrCode">
    <div class="container">
        <div class="qrcode">
            <div style="width: 100vw;" id="reader"></div>
        </div>
     </div>
    <div class="btn">
        <div class="left-back">
            <el-icon  @click="clickBack"><ArrowLeft /></el-icon>
        </div>
   </div>
</div>

js

  <script setup lang="ts">
  import { Html5Qrcode } from "html5-qrcode"
  import { onUnmounted } from "vue";
  let isQrCode = ref(false)
  let html5QrCode:Html5Qrcode = null; let data = reactive({
    form:{
      code:''
    }
  })
 let openQrcode =()=>{
    isQrCode.value =true
     getCamerasD()
  }
  // 使用相机扫码
   const getCamerasD = () => {
        Html5Qrcode.getCameras().then((devices) => {
            if (devices && devices.length) {
              html5QrCode = new Html5Qrcode('reader')
              startss(devices)
            }
          }).catch((err) => {
            alert('摄像头无访问权限')
      })
  }
  const startss = (devices) => {
        const config = {
          fps: 10, //  二维码扫描每秒帧数
          qrbox: { width: 300, height: 300 }, // UI框的大小
        }
        if (devices && devices.length) {
          html5QrCode.start( { facingMode: 'environment' }, config, qrCodeSuccessCallback)
          .catch((err) => {
            let message = ''
            // 错误信息处理仅供参考,具体描述自定义
            if (typeof err == 'string') {
              message = '二维码识别失败!'
            } else {
              if (err.name == 'NotAllowedError') {
                message = '您需要授予相机访问权限!'
              }
              if (err.name == 'NotFoundError') {
                message = '这个设备上没有摄像头!'
              }
              if (err.name == 'NotSupportedError') {
                message = '摄像头访问只支持在安全的上下文中,如https或localhost!'
              }
              if (err.name == 'NotReadableError') {
                message = '相机被占用!'
              }
              if (err.name == 'OverconstrainedError') {
                message = '安装摄像头不合适!'
              }
              if (err.name == 'StreamApiNotSupportedError') {
                message = '此浏览器不支持流API!'
              }
            }
          })
        }
     }

 // 扫码成功的回调
  const qrCodeSuccessCallback = res => {
      data.form.code = res
      isQrCode.value =false
      stop()
  }
  let clickBack = ()=>{
    isQrCode.value =false
  }
  onUnmounted(() => {
     //扫描设备是否在运行
     if (html5QrCode.isScanning) {
        stop()
     }
   })
   const stop = () => {
       html5QrCode.stop().then((ignore) => {
        alert('停止扫码', ignore)
    }).catch((err) => {
        alert('停止扫码失败')
     })
    }
 </script>