业务场景:H5中用到扫码的场景,常见扫码签到、扫码签退
框架:vue
依赖:npm i html5-qrcode
<template>
<div>
<div class="fx_qrcode">
<div id="reader" width="600px"></div>
</div>
</div>
</template>
<script>
import { Html5Qrcode } from 'html5-qrcode';
export default {
data() {
return {};
},
mounted() {
this.getCameras();
},
methods: {
getCameras() {
Html5Qrcode.getCameras()
.then(devices => {
/**
* 获取摄像头
*/
if (devices && devices.length) {
// 如果有2个摄像头,1为前置的
if (devices.length > 1) {
this.cameraId = devices[1].id;
} else {
this.cameraId = devices[0].id;
}
this.devices = devices;
this.start();
}
})
.catch(err => {
});
},
//开始扫码
start() {
const self = this;
this.html5QrCode = new Html5Qrcode('reader');
this.html5QrCode
.start(
this.cameraId,
{
fps: 10,
qrbox: { width: 250, height: 250 },
},
(decodedText, decodedResult) => {
//获取到二维码中的信息
this.handleRequest(decodedText);
},
errorMessage => {
},
)
.catch(err => {
});
},
//结束扫码
stop() {
this.html5QrCode
.stop()
.then(ignore => {
})
.catch(err => {
});
},
async handleRequest(decodedText) {
//根据二维码中的信息发送请求处理业务
},
},
};
</script>
<style>
.fx_qrcode {
margin-top: 200px;
}
</style>