最近接到一个需求 在微信无法调用扫一扫时 调取浏览器环境的扫一扫 然后解析二维码数据 也是第一次做 记录一下 希望能帮到同学们
首先我们需要一个第三方库 叫做Html5Qrcode
下载
npm install Html5Qrcode
引入
import { Html5Qrcode } from "html5-qrcode";
然后在点击调取摄像头时 调取这个函数
/**
* web https 调起摄像头
*/
onWebScan() {
// 获取摄像头在页面创建时使用
Html5Qrcode.getCameras()
.then((devices) => {
console.log(devices);
if (devices && devices.length) {
this.cameraId = devices[0].id;
} else {
this.cameraId = devices[1].id;
}
this.devices = devices;
this.html5Qrcode = new Html5Qrcode("reader");
this.start();
})
.catch((e) => {
this.html5Qrcode = new Html5Qrcode("reader");
console.log("Error: " + e, "onWebScan报错");
});
},
html5分别有开始方法 和结束的方法 都贴在下面
/**
* 获取扫码内容
*/
start() {
this.html5Qrcode
.start(
this.cameraId,
{
fps: 10,
qrbox: { width: 250, height: 250 },
},
(decodedText, decodedResult) => {
//这里是成功的回调
console.log(
decodedText,
decodedResult,
"decodedText,decodedResult"
);
//我这里获取了解码后的msg 然后处理自己的业务
this.ResultCodeText = decodedText
this.stopCreamer();
this.onConfirm();
},
(errorMessage) => {
// console.log(errorMessage);
}
)
.catch((e) => {
console.log("Error: " + e, "start报错#####");
});
},
/**
* 结束调用
*/
stopCreamer() {
console.log("进入结束调用");
this.html5Qrcode
.stop()
.then((ignore) => {
console.log(ignore, "结束调用");
})
.catch((err) => {
console.log("结束调用报错信息");
});
},