最近遇到一个比较麻烦的需求,简单的在这里记录一下,下次要用的时候还会有迹可循
实现h5的二维码扫描,uniapp看了一遍发现不支持h5
经过大量的查找,只能实现模仿扫码功能,如果有需要的直接拿走,要是有大牛能有更好的方法,麻烦指点一二
1、在项目的utils文件下创建reqrcode.js文件,在需要使用的项目中引入(点这里获取reqrcode.js)
import qrcode from '@/utils/reqrcode.js'
2、一下是js部分直接使用
const scanBtn = () => {
// #ifdef APP-PLUS
scanCodeAPP()
// #endif
// #ifdef H5
scanCodeH5()
// #endif
}
const scanCodeApp = () => {
uni.scanCode({
scanType: ['qrCode'],
success: (res) => {
console.log(res)
}
})
}
const scanCodeH5 = () => {
uni.chooseImage({
count: 1,
success: (imgRes) => {
qrcode.qrcode.decode(getObjectURL(imgRes.tempFiles[0]))
qrcode.qrcode.callback = (codeRes) => {
if (codeRes.indexOf('error') >= 0) {
// 二维码识别失败
uni.showToast({
title: '识别失败',
icon: 'error'
})
} else {
// 二维码识别成功
let r = decodeStr(codeRes)
wxsuccessFn(r)
}
}
}
})
}
// 获取文件地址函数
const getObjectURL = (file) => {
var url = null
if (window.createObjectURL !== undefined) { // basic
url = window.createObjectURL(file)
} else if (window.URL !== undefined) { // mozilla(firefox)
url = window.URL.createObjectURL(file)
} else if (window.webkitURL !== undefined) { // webkit or chrome
url = window.webkitURL.createObjectURL(file)
}
return url
}
// 扫码成功解析设备号
const wxsuccessFn = async (url) => {
let res = await analyzeCode(url)
scanList.value.push({
col: (minCols.value + scanList.value.length),
dno: res.deviceCode,
row: selectRowNumber.value
})
}