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}
相关推荐
cecyci1 分钟前
如何实现AI聊天机器人的打字机效果?
前端·javascript
IT_陈寒5 分钟前
Vite 5个隐藏技巧让你的项目构建速度提升50%,第3个太香了!
前端·人工智能·后端
詩句☾⋆᭄南笙14 分钟前
HTML的盒子模型
前端·html·盒子模型
落言15 分钟前
AI 时代的工程师:懂,却非懂的时代
前端·程序员·架构
一枚攻城狮18 分钟前
前端知识点大汇总
前端
余道各努力,千里自同风1 小时前
el-input 输入框宽度自适应宽度
javascript·vue.js·elementui
Mike_jia1 小时前
DumbAssets:开源资产管理神器,家庭与企业的高效管家
前端
Southern Wind2 小时前
Vue 3 多实例 + 缓存复用:理念及实践
前端·javascript·vue.js·缓存·html
HuangYongbiao2 小时前
Rspack 原理:webpack,我为什么不要你
前端
yinuo2 小时前
前端项目开发阶段崩溃?试试这招“Node 内存扩容术”,立马复活!
前端