<template>
  <div>
    <div>{{res}}</div>
    <!-- 扫描仪占位符 -->
    <div id="reader"></div>
  </div>
</template>

<script>
import { Html5Qrcode } from "html5-qrcode"
export default {
  data() {
    return {
      res: null,
      html5QrCode: null,
    }
  },
  mounted() {
    this.useCamera() // 打开相机
  },
  methods: {
    // 关闭扫一扫页面，返回上一页
    closed() {
      this.html5QrCode.stop().finally(() => {
        this.html5QrCode.clear()
      })
    },
    scanRes(qr, err) {
      this.res = qr
    },
    // 成功回调
    onScanSuccess(qr) {
      this.scanRes(qr)
      this.closed()
    },
    useCamera() {
      alert(1)
      // 实例化，接收元素id作为参数
      this.html5QrCode = new Html5Qrcode("reader")
      // 获取相机设备
      Html5Qrcode.getCameras()
          .then(devices => {
            // 扫码配置
            const config = {
              fps: 10, //  二维码扫描每秒帧数
              qrbox: {
                width: 300,
                height: 300,
              }, // UI框的大小
              aspectRatio: 1.777778,
            }
            if (devices && devices.length) {
              let cameraId = devices[devices.length - 1].id //后置摄像头，一般最后一个是后置摄像头
              //let cameraId = devices[0].id //前置摄像头
              this.html5QrCode
                  .start({ deviceId: { exact: cameraId, }, }, config, this.onScanSuccess)
                  .catch(err => {
                    this.scanRes(undefined, err)
                  })
            } else {
              // 如果没有找到设备，直接启用摄像头
              //environment：后置摄像头  user：前置摄像头
              this.html5QrCode
                  .start( { facingMode: "environment" }, config, this.onScanSuccess )
                  .catch(err => {
                    alert('error')
                    this.scanRes(undefined, err)
                  })
            }
          })
          .catch(err => {
            this.scanRes(undefined, err)
          })
    },
  },
}
</script>
