1. vue-qrcode-reader
在浏览器端html中有一款依赖可以直接调用摄像头扫码,vue-qrcode-reader。 分别提供QrcodeStream、QrcodeDropZone、QrcodeCapture用来识别二维码。
- QrcodeStream: 调用摄像头扫码
- QrcodeDropZone:将图片移到识别区域内识别二维码
- QrcodeCapture:选择原生拍照或者图片到浏览器识别二维码。
2. 安装
npm install vue-qrcode-reader
3. QrcodeStream直接调用摄像头扫码
- init方法是初始化调用摄像头,此时如果摄像头报错会有很多提示,请酌情处理
- decode方法,当识别到二维码会把识别信息触发出来
<template>
<div>
<p class="error">{{ error }}</p>
<p class="decode-result">Last result: <b>{{ result }}</b></p>
<qrcode-stream @decode="onDecode" @init="onInit" />
</div>
</template>
<script>
import { QrcodeStream } from 'vue-qrcode-reader'
export default {
components: { QrcodeStream },
data () {
return {
result: '',
error: ''
}
},
methods: {
onDecode (result) {
this.result = result
},
async onInit (promise) {
try {
await promise
} catch (error) {
if (error.name === 'NotAllowedError') {
this.error = "ERROR: you need to grant camera access permission"
} else if (error.name === 'NotFoundError') {
this.error = "ERROR: no camera on this device"
} else if (error.name === 'NotSupportedError') {
this.error = "ERROR: secure context required (HTTPS, localhost)"
} else if (error.name === 'NotReadableError') {
this.error = "ERROR: is the camera already in use?"
} else if (error.name === 'OverconstrainedError') {
this.error = "ERROR: installed cameras are not suitable"
} else if (error.name === 'StreamApiNotSupportedError') {
this.error = "ERROR: Stream API is not supported in this browser"
} else if (error.name === 'InsecureContextError') {
this.error = `ERROR: Camera access is only permitted in secure context.
Use HTTPS or localhost rather than HTTP.`;
} else {
this.error = `ERROR: Camera error (${error.name})`;
}
}
}
}
}
</script>
<style scoped>
.error {
font-weight: bold;
color: red;
}
</style>
4. 针对部分IOS【Vue warn】错误
TypeError: Reflect.construct requires the first argument to be a constructor 我目前没有更好的解决办法,只能充分利用vue生命周期中的捕获错误处理 errorCaptured。
有个开发说新版本不支持的
5. QrcodeCapture用原生拍照或者直接选择图片识别
decode方法和QrcodeStream一致,如果识别到了二维码将触发该事件。
<template>
<div>
<p>
Capture:
<select v-model="selected">
<option v-for="option in options" :key="option.text" :value="option">
{{ option.text }}
</option>
</select>
</p>
<hr/>
<p class="decode-result">Last result: <b>{{ result }}</b></p>
<qrcode-capture @decode="onDecode" :capture="selected.value" />
</div>
</template>
<script>
import { QrcodeCapture } from 'vue-qrcode-reader'
export default {
components: { QrcodeCapture },
data () {
const options = [
{ text: "rear camera (default)", value: "environment" },
{ text: "front camera", value: "user" },
{ text: "force file dialog", value: false },
]
return {
result: '',
options,
selected: options[0]
}
},
methods: {
onDecode (result) {
this.result = result
}
}
}
</script>
注意:选择图片识别的识别率不是很高,但是已经是planB了,可以试试更好的planB或者让作者再努力一下。
完整demo
|