安装@zxing/library
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() {
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() {
let videoBoxDom = document.getElementById('videoBox')
let videoDom = document.createElement('video')
videoDom.id = 'video'
videoDom.style.position = 'absolute'
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>