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}
相关推荐
devincob43 分钟前
js原生、vue导出、react导出、axios ( post请求方式)跨平台导出下载四种方式的demo
javascript·vue.js·react.js
编程社区管理员44 分钟前
React 发送短信验证码和验证码校验功能组件
前端·javascript·react.js
葡萄城技术团队1 小时前
迎接下一代 React 框架:Next.js 16 核心能力解读
javascript·spring·react.js
全马必破三1 小时前
React“组件即函数”
前端·javascript·react.js
三思而后行,慎承诺1 小时前
React 底层原理
前端·react.js·前端框架
座山雕~1 小时前
html 和css基础常用的标签和样式
前端·css·html
課代表1 小时前
JavaScript 中获取二维数组最大值
javascript·max·数组·递归·array·最大值·二维
灰小猿2 小时前
Spring前后端分离项目时间格式转换问题全局配置解决
java·前端·后端·spring·spring cloud
im_AMBER2 小时前
React 16
前端·笔记·学习·react.js·前端框架
02苏_2 小时前
ES6模板字符串
前端·ecmascript·es6