h5的扫一扫功能 (非微信浏览器环境下)

必须在 https 域名下才生效

html 复制代码
<template>
	<div>
		<van-field label="服务商编码" right-icon="scan" placeholder="扫描二维码获取" @click-right-icon="getCameras" />    
		<div class="scan" :style="{'display':isScan ? 'none' : ''}">
			<div id="qr-reader" width="400px" height="400px">
		</div>
	</div>
</template>
javascript 复制代码
<script>
import util from "../common/util.js";
export default {
  data() {
    return {
      cameraId: 0,//相机id
      isScan:true,
    };
  },
  mounted() {
   	this.init();
  },
  // 页面销毁周期关闭相机
  beforeDestroy() {
     this.stop();
  },
  methods: {
    init() {
    	util.addJs("https://blog.minhazav.dev/assets/research/html5qrcode/html5-qrcode.min.js");
    },
    // 开始扫描
    getCameras() {
       Html5Qrcode.getCameras().then(devices => {
         if(devices){
           if (devices.length==1) {
             this.cameraId = devices[0].id;
           }else{
             this.cameraId = devices[1].id;
           }
           this.start();
         }
       }).catch(err => {
         this.$notify({ 
           type: 'warning', 
           message: '调用摄像头失败 : ' + err
         });
       });
     },
     // 启动相机
     start() {
       this.isScan = false;
       this.html5QrCode = new Html5Qrcode("qr-reader");
       this.html5QrCode.start(
         this.cameraId,
         {
           fps: 10,
           qrbox: { width: 250, height: 250 }
         },
         qrCodeMessage => {
           if (qrCodeMessage) {
             this.stop();
           }
         }
       ).catch(err => {
         console.log(`Unable to start scanning, error: ${err}`);
       });
     },
     // 关闭相机
     stop() {
       this.isScan = true;
       this.html5QrCode.stop().then(ignore => {
         console.log("QR Code scanning stopped.");
       }).catch(err => {
         console.log("Unable to stop scanning.");
       });
     },
  }
};
</script>
css 复制代码
<style lang="less" scoped>
	.scan{
		width: 100%;
		height: 100vh;
		display: flex;
		align-items: center;
		justify-content: center;
		flex-direction: column;
		overflow: hidden;
	}
</style>

util.js文件

javascript 复制代码
const addJs=function (url) {
	return new Promise((resolve, reject) => {
		const script = document.createElement('script')
		script.src = url
		script.type = 'text/javascript'
		document.body.appendChild(script)
		script.onload = () => {
			resolve()
		}
	})
}
export default {addJs}
相关推荐
甲维斯1 小时前
完蛋了,豆包变这么强?Seed2.1pro小测一下!
前端·人工智能
烈风逍遥1 小时前
第一篇:SeaPack 全栈项目工程化实践
前端·后端·架构
烈风逍遥1 小时前
第二篇:SeaPack 权限体系:从"谁都能看"到"该看什么看什么"
前端·后端·架构
Z_Quintaz1 小时前
关于导航栏颜色透明这件事
前端·debug
默_笙1 小时前
🚅 地铁的"回头路、存档点与人工闸机"(下):LangGraph 的循环、持久化与中断
前端·javascript
flash俊杰1 小时前
Zod Schema 驱动的 IPC 契约:从入参校验到状态机一致性的三层防御
javascript·typescript
ClouGence1 小时前
Chrome Recorder 能用于长期回归测试吗?
前端·chrome·测试
拖孩1 小时前
这个小程序是 AI 帮我写的,可它里面一个 AI 功能都没有
前端·后端·微信小程序
Nayana3 小时前
《Web 到 HarmonyOS》-- 业务分析:消息推送业务方法
前端