当前位置:

使用html5-qrcode 扫描二维码(vue3)

访客 2024-04-24 1344 0

使用html5-qrcode

npm地址

1.安装

npmihtml5-qrcode

2.使用

<template><divclass="container"><divid="reader"></div></div></template><scriptsetuplang="ts">import{onMounted,ref}from'vue';import{useRouter}from'vue-router';import{Html5Qrcode}from'html5-qrcode';import{Html5QrcodeResult,CameraDevice}from'./interface';letcameraId=ref('');letdevicesInfo=ref<any>('');lethtml5QrCode=ref<any>(null);constrouter=useRouter();onMounted(()=>{getCameras();});onUnmounted(()=>{stop();});constgetCameras=()=>{Html5Qrcode.getCameras().then((devices:CameraDevice[])=>{console.log('摄像头信息',devices);if(devices&&devices.length){//如果有2个摄像头,1为前置的if(devices.length>1){cameraId.value=devices[1].id;}else{cameraId.value=devices[0].id;}devicesInfo.value=devices;//start开始扫描start();}}).catch((err)=>{//handleerrconsole.log('获取设备信息失败',err);//获取设备信息失败});};conststart=()=>{html5QrCode=newHtml5Qrcode('reader');html5QrCode.start(cameraId.value,//retreivedinthepreviousstep.{fps:10,//设置每秒多少帧qrbox:{width:250,height:250},//设置取景范围//scannable,restshaded.},(decodedText:string,decodedResult:Html5QrcodeResult)=>{//dosomethingwhencodeisread.Forexample://if(qrCodeMessage){//getCode(qrCodeMessage);//stop();//}console.log('扫描的结果',decodedText,decodedResult);//if(decodedText){//router.push('order');//}},(errorMessage:any)=>{//parseerror,ideallyignoreit.Forexample://console.log(`QRCodenolongerinfrontofcamera.`);console.log('暂无额扫描结果',errorMessage);}).catch((err:any)=>{//Startfailed,handleit.Forexample,console.log(`Unabletostartscanning,error:${err}`);});};conststop=()=>{html5QrCode.stop().then((ignore:any)=>{//QRCodescanningisstopped.console.log('QRCodescanningstopped.',ignore);}).catch((err:any)=>{//Stopfailed,handleit.console.log('Unabletostopscanning.',err);});};</script><stylelang="scss"scoped>.container{position:relative;height:100%;width:100%;background:rgba($color:#000000,$alpha:0.48);}#reader{top:50%;left:0;transform:translateY(-50%);}</style>

3.类型

exportinterfaceCameraDevice{id:string;label:string;}/***Codeformatssupportedbythislibrary.*/enumHtml5QrcodeSupportedFormats{QR_CODE=0,AZTEC,CODABAR,CODE_39,CODE_93,CODE_128,DATA_MATRIX,MAXICODE,ITF,EAN_13,EAN_8,PDF_417,RSS_14,RSS_EXPANDED,UPC_A,UPC_E,UPC_EAN_EXTENSION,}classQrcodeResultFormat{//@ts-ignorepublicreadonlyformat:Html5QrcodeSupportedFormats;//@ts-ignorepublicreadonlyformatName:string;}/**Detailedscanresult.*/exportinterfaceQrcodeResult{/**Decodedtext.*/text:string;/**Formatthatwassuccessfullyscanned.*/format?:QrcodeResultFormat;}/**QrCoderesultobject.*/exportinterfaceHtml5QrcodeResult{decodedText:string;result:QrcodeResult;}

发表评论

  • 评论列表
还没有人评论,快来抢沙发吧~