项目需求:H5项目需要实现扫描二维码或条形码功能。
html5-qrcode使用
1.安装
npm install html5-qrcode --save-dev
2.引入
import { Html5Qrcode } from 'html5-qrcode';
3.定义所需变量
data: function() {
return {
html5QrCode: null,
isShow: false,
scanReasonList: []
};
},
4.创建容器(可根据需求写样式)
<div class="reader" v-if="isShow">
<div id="reader-box"></div>
</div>
5.实现扫码逻辑
在一个button或者其他节点上绑定事件“scanCode”
scanCode() {
this.startScan();
},
startScan() {
this.isShow = true;
Html5Qrcode.getCameras().then(devices => {
if (devices && devices.length) {
this.html5Qrcode = new Html5Qrcode('reader-box');
this.html5Qrcode.start(
{
facingMode: 'environment'
},
{
fps: 10,
qrbox: { width: 250, height: 250 }
},
(decodeText, decodeResult) => {
if (decodeText) {
this.scanReasonList.push(decodeText);
this.stopScan();
this.isShow = false;
}
},
err => {
console.log('失败', err);
}
);
}
});
},
stopScan() {
this.html5Qrcode.stop();
},
至此,可基本实现扫码功能。具体的参数配置可参考官网 Getting started | ScanApp