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}
相关推荐
Avan_菜菜3 小时前
AI 能写代码了,为什么我反而开始要求它先写文档?
前端·github·ai编程
JieE2126 小时前
LeetCode 226. 翻转二叉树|JS 递归超详细拆解,二叉树入门经典题
javascript·算法
JieE2127 小时前
LeetCode 104. 二叉树的最大深度|递归思路超详细拆解
javascript·算法
爱勇宝7 小时前
鸿蒙生态的下半场:开发者不只要能开发,还要能赚钱
android·前端·程序员
IT_陈寒10 小时前
SpringBoot这个自动配置坑我跳了三次
前端·人工智能·后端
kyriewen10 小时前
我用 AI 一周写完了整个项目,上线第一天就崩了——这是我踩过最贵的 5 个坑
前端·javascript·ai编程
Larcher11 小时前
AI Loop:让AI像人一样自主完成任务的核心机制
javascript·人工智能·设计模式
默_笙11 小时前
🃏 JS 只有 8 种数据类型,但我花了 2 天才搞懂 null 和 undefined 的区别
javascript
牧艺11 小时前
从零到协同:构建类飞书在线文档系统的五个技术重难点
前端·人工智能
jump_jump11 小时前
流式 HTML:从 htmx 片段装配到浏览器原生增量渲染
javascript·性能优化·前端工程化