赞
踩
提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
提示:以下是本篇文章正文内容,下面案例可供参考
描述:uniapp不支持H5扫描二维码,只能自己写方法。
代码如下(示例):
<template>
<view class="scan size">
<u-navbar back-text="二维码扫描"></u-navbar>
<view class="sectionview"><view id="qr-reader" style="width:100%;height:100%;"></view></view>
</view>
</template>
代码如下(示例):
<script>
export default {
data() {
return {
cameraId: '',
};
},
mounted() {
this.init();
},
beforeDestroy() {//页面销毁时,关闭摄像头
this.stop();
},
methods: {
//返回结果
getCode(id) {
if (!id) return;
//跳转页面
uni.switchTab({
url:`/pages/menu/index`
})
uni.setStorageSync("id",id)
},
init() {
this.AddJs('https://blog.minhazav.dev/assets/research/html5qrcode/html5-qrcode.min.js');
//需要加载时间建议延时一点再获取设备列表
setTimeout(() => {
this.getCameras();
}, 1000);
},
stop() {
this.html5QrCode
.stop()
.then(ignore => {
// QR Code scanning is stopped.
console.log('QR Code scanning stopped.');
})
.catch(err => {
// Stop failed, handle it.
console.log('Unable to stop scanning.');
});
},
start() {
this.html5QrCode = new Html5Qrcode('qr-reader');
this.html5QrCode
.start(
this.cameraId, // retreived in the previous step.
{
fps: 10, // sets the framerate to 10 frame per second
qrbox: 250 // sets only 250 X 250 region of viewfinder to
// scannable, rest shaded.
},
qrCodeMessage => {
// do something when code is read. For example:
if (qrCodeMessage) {
uni.showToast({
title: '扫码成功',
icon: 'success'
});
this.getCode(qrCodeMessage);
this.stop();
}
},
errorMessage => {
// parse error, ideally ignore it. For example:
// console.log(`QR Code no longer in front of camera.`);
}
)
.catch(err => {
// Start failed, handle it. For example,
console.log(`Unable to start scanning, error: ${err}`);
this.$refs.uToast.show({
title: `扫码失败:${err}`,
type: 'error'
});
});
},
getCameras() {
Html5Qrcode.getCameras()
.then(devices => {
/**
* devices would be an array of objects of type:
* { id: "id", label: "label" }
*/
if (devices && devices.length) {
if (devices.length > 1) {
this.cameraId = devices[1].id;
} else {
this.cameraId = devices[0].id;
}
this.start();
}
})
.catch(err => {
this.$refs.uToast.show({
title: '启用相机失败',
type: 'error'
});
});
},
//动态创建script的方法
AddJs(url) {
//console.log( 'url:',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();
};
});
}
}
};
</script>
---
# 总结
提示:H5扫描二维码
我也看了很多方法,很多都是需要引入插件特别麻烦,这个直接可以使用。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。