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}
相关推荐
英俊潇洒美少年7 分钟前
react19和vue3的优缺点 对比
前端·javascript·vue.js·react.js
~无忧花开~2 小时前
React生命周期全解析
开发语言·前端·javascript·react.js·前端框架·react
哈__2 小时前
ReactNative项目OpenHarmony三方库集成实战:react-native-maps
javascript·react native·react.js
诗句藏于尽头2 小时前
基于GPT2的底模微调实现微信聊天风格模仿输出
学习·微信
cj81402 小时前
Prompt,Agent,Skill,Mcp分别于langchain有什么关系
前端
SuperEugene3 小时前
Axios + Vue 错误处理规范:中后台项目实战,统一捕获系统 / 业务 / 接口异常|API 与异步请求规范篇
前端·javascript·vue.js·前端框架·axios
行走的陀螺仪3 小时前
手写 Vue3 极简 i18n
前端·javascript·vue.js·国际化·i18n
羽沢313 小时前
一篇简单的STOMP教程QAQ
前端·javascript·stomp
code_Bo3 小时前
使用AI完成Swagger接口类型在前端自动生成的工具
前端·后端·架构