扫描二维码

本文介绍了如何在Vue.js项目中使用html5-qrcode库进行二维码扫描,包括获取相机权限、启动和停止扫描以及处理扫描结果的方法。同时,提到了在Android和iOS平台上的适配需求。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

使用的html5-qrcode库,兼容app中H5扫码,需要Andriod同事调试下打开相机权限,需要iOS同事调试

参考文章:这里进入

  1. npm install
npm install html5-qrcode
  1. 新建个qrcode.vue组件:
<template>
  <div class="qrcode">
    <div id="reader" />
  </div>
</template>

<script>
import { Html5Qrcode } from 'html5-qrcode'
export default {
  created() {
    this.getCameras()
  },
  beforeDestroy() {
    this.stop()
  },
  methods: {
    getCameras() {
      Html5Qrcode.getCameras().then((devices) => {
        if (devices && devices.length) {
          this.html5QrCode = new Html5Qrcode('reader')
          this.start()
        }
      }).catch((err) => {
        // handle err
        console.log(err)
        this.html5QrCode = new Html5Qrcode('reader')
        this.error = 'ERROR: 您需要授予相机访问权限'
        this.$emit('err', this.error)
      })
    },
    start() {
      // environment后置 user前置
      this.html5QrCode.start(
        { facingMode: 'environment' },
        {
          fps: 2,
          qrbox: { width: 250, height: 250 }
        },
        (decodedText, decodedResult) => {
          this.$emit('ok', decodedText)
        }
      ).catch((err) => {
        this.$emit('err', err)
      })
    },
    stop() {
      this.html5QrCode.stop().then((ignore) => {
        // QR Code scanning is stopped.
        console.log('QR Code scanning stopped.')
      }).catch((err) => {
        // Stop failed, handle it.
        console.log('Unable to stop scanning.', err)
      })
    }
  }
}
</script>

<style lang="scss" scoped>
	.qrcode{
		position: relative;
		height: 100%;
		width: 100%;
		background: rgba($color: #000000, $alpha: 0.48);
	}
	#reader{
    top: 0%;
		left: 0;
	}
</style>
  1. 引用
<template>
  <BarScan
    ref="qrcode"
    @ok="getResult"
    @err="geterror"
  />
</template>
<script>
import BarScan from '@/components/BarScan.vue'
import Vconsole from 'vconsole' // 打印工具

export default {
  components: {
    BarScan
  },
  mounted() {
    const vconsole = new Vconsole()
  },
  methods: {
    getResult(result) {
      this.result = result
      console.log(4444, result)
    },
    geterror(e) {
      console.log(5555, e)
    } }
}
</script>

很赞同村上春树的一句话:

“有一个喜欢的人真的太重要了,在你打算稀里糊涂过这普普通通的一生的时候,会因为对方而再想努力一下,在那么多疲惫不堪甚至抬不起头的日子,会因为对方而觉得人生还有盼头。”正确的爱是良性的相互教育,是强有力的向上攀爬,是治愈彼此人生滚烫的阳光。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值