1.安装依赖包
npm install @zxing/library -S
2.项目中使用
<template>
<video :id="vId" autoplay style="width: 100%; height: 500px;"></video>
</template>
<script>
import { BrowserMultiFormatReader } from '@zxing/library';
export default {
data() {
return {
vId: 'codeVideo',
codeReader: new BrowserMultiFormatReader(),
};
},
created() {
this.scanCode();
},
methods: {
scanCode() {
this.codeReader.getVideoInputDevices().then((videoInputDevices) => {
const leng = videoInputDevices.length;
if (!leng) {
return console.error( '找不到摄像头');
}
const deviceId = videoInputDevices[leng - 1].deviceId;
this.codeReader.decodeFromInputVideoDeviceContinuously(deviceId, this.vId, (result, err) => {
if (result) {
console.error(result.text);
}
if (err) {
console.error(err);
}
});
}).catch(err => {
console.error(err);
}).finally(() => {
this.codeReader.reset(); // 销毁扫描
});
},
},
}
</script>
3.注意事项
摄像头必须在 https 下才能获取到,在 vue.config.js 文件中添加以下代码:
module.exports = {
devServer: {
https: true, // 添加这一行代码
},
};
然后运行 npm run serve
重启项目