如何使用Vue实现一个H5扫码功能?
安装 @zxing/library 依赖 npm i @zxing/library --save;
需要注意的是 一定要在https环境下使用!一定要在https环境下使用!一定要在https环境下使用!重要的事情说三遍。否则摄像头调用不出来。
<template><div class="page-scan"><!-- 扫码区域 --><video ref="video" id="video" class="scan-video" autoplay></video><!-- 提示语 --><div v-show="msgShow" class="scan-msg">{{ message}}</div></div>
</template>
<script>
import { BrowserMultiFormatReader } from "@zxing/library";
export default {name: "scanRegion",data() {return {codeReader: null,scanText: "",message: "正在扫描",msgShow: false,};},created() {this.codeReader = new BrowserMultiFormatReader();this.openScan();},// 记得销毁,要不然返回再进去会不显示destroyed() {this.codeReader.reset();},methods: {openScan() {this.codeReader.getVideoInputDevices().then((videoInputDevices) => {this.tipShow = true;this.tipMsg = "正在调用摄像头...";// 因为获取的摄像头有可能是前置有可能是后置,但是一般最后一个会是后置,所以在这做一下处理// 默认获取第一个摄像头设备idlet firstDeviceId = videoInputDevices[0].deviceId;if (videoInputDevices.length > 1) {// 获取后置摄像头let deviceLength = videoInputDevices.length;--deviceLength;firstDeviceId = videoInputDevices[deviceLength].deviceId;}this.decodeFromInputVideoFunc(firstDeviceId);}).catch((err) => {this.tipShow = false;console.error(err);});},decodeFromInputVideoFunc(firstDeviceId) {this.codeReader.reset(); // 重置this.scanText = "";this.codeReader.decodeFromInputVideoDeviceContinuously(firstDeviceId,"video",(result, err) => {this.tipMsg = "正在尝试识别...";this.scanText = "";if (result) {// 获取到的是二维码内容,然后在这个if里面写业务逻辑即可this.scanText = result.text;if (this.scanText) {this.tipShow = false;this.codeReader.reset();let params = {scId: this.$route.query.scId,qrcode: this.scanText}this.$axios.post('/medapp/api/scanner/user/scanner/add',params).then(res => {if (res.data.code == 0) {this.$router.push({path: '/scansuccess',query: {scId: this.$route.query.scId,regId: res.data.data.regId,regName: res.data.data.regName,regPhone: res.data.data.regPhone,regOrg: res.data.data.regOrg,}})} else {this.$router.push({path: '/scanerror',query: {scId: this.$route.query.scId,msg: res.data.msg}})}})}}if (err && !err) {this.message= "识别失败";setTimeout(() => {this.msgShow = false;}, 2000);console.error(err);}});},},
};
</script><style lang="scss" scoped>
.scan-video {width: 100%;height: 80vh;
}
.scan-msg {width: 100vw;text-align: center;margin-bottom: 10vh;color: white;font-size: 5vw;
}
.page-scan {width: 100vw;background-color: #363636;
}
</style>
以上就是实现一个扫码的基本内容,其中还会有很多可以优化的,比如扫码成功后停顿一下,做一个动态的框这些,有感兴趣的可以试试,分享一下;
PS:以上本人自己试验以及搜集网上内容实现的,如有不足请指出