赞
踩
yarn add @zxing/library 或npm i @zxing/library --save
<script> import { BrowserQRCodeReader } from '@zxing/library' export default { data() { return { codeReader: new BrowserQRCodeReader() } }, async onLoad(options) { await this.fetchData() }, destroyed() { this.removeDom() }, methods: { async fetchData() { // 先删除已存在的dom this.removeDom() // 再创建 this.createDom() await this.openCameraAndScan() }, // 打开摄像头 async openCameraAndScan() { try { await this.newScan() } catch (err) { console.log(err) if (err.code && err.code == 404) { uni.showToast({ title: '浏览器不支持,请更换浏览器', duration: 2000, icon: 'error' }) } else { uni.showToast({ title: '请检查是否存在摄像头', duration: 2000, icon: 'error' }) } } }, async newScan() { // 构建回调函数 const handleQrCode = (result, err) => { if (result && result.text) { // 判断是否其他网点 console.log("扫码出的结果",result.text) } if (err && !err) { this.removeDom() uni.showToast({ title: '摄像头扫码失败', duration: 2000, icon: 'error' }) } } let result, err try { console.log('初始化zxing') let videoDom = document.getElementById('video') result = await this.codeReader.decodeOnceFromVideoDevice(undefined, videoDom) console.log('扫码结果', result) } catch (ex) { console.error('zxing识别错误', ex) err = ex } // 调用回调函数 handleQrCode(result, err) }, createDom() { // 手动创建html video // 否则,如果是template中的video,会被转译成univideo // 导致zxing无法识别 let videoBoxDom = document.getElementById('videoBox') let videoDom = document.createElement('video') videoDom.id = 'video' videoDom.style.position = 'absolute' // videoDom.style.zIndex = '-2' videoDom.style.width = '100%' videoDom.style.height = '100%' videoDom.style.objectFit = 'cover' videoDom.setAttribute('autoplay', true) videoDom.setAttribute('muted', true) videoBoxDom.appendChild(videoDom) }, removeDom() { if (this.codeReader && this.codeReader.reset) { this.codeReader.reset() } if (this.codeReader && this.codeReader.reader && this.codeReader.reader.reset) { this.codeReader.reader.reset() } let videoBoxDom = document.getElementById('videoBox') let videoDom = document.getElementById('video') if (videoBoxDom && videoDom) { videoBoxDom.removeChild(videoDom) } } } } </script>
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。