赞
踩
移动端实现扫一扫,对二维码或者条形码进行识别
二维码的识别有很多插件,比如:vue-qrcode-reader,@zxing/library,但是vue-qrcode-reader无法识别条形码,最后选择了@zxing/library,这里记录一下:
一、安装插件 使用cnpm或者yarn都可以
cnpm install @zxing/library -S
二、上代码
- <template>
- <div class="container">
- <video ref="video" id="video" class="scan-video" autoplay></video>
- </div>
- </template>
-
- <script>
- import { BrowserMultiFormatReader } from '@zxing/library'
- export default {
- name: 'ProductTraceUiCeshi',
-
- data() {
- return {
- codeReader: null,
- deviceId: '',
- }
- },
- mounted() {
- this.codeReader = new BrowserMultiFormatReader()
- this.openScan()
- },
- beforeDestroy() {
- this.codeReader.reset()
- },
-
- methods: {
- openScan() {
- let that = this
- this.codeReader
- .getVideoInputDevices()
- .then((devices) => {
- if (devices && devices.length > 0) {
- let length = devices.length
- that.deviceId =
- length > 1 ? devices[length - 1].deviceId : devices[0].deviceId
- that.setDecode()
- }
- })
- .catch(() => {
- this.$toast('无法获取照相机')
- })
- },
- setDecode() {
- let that = this
- that.codeReader.reset()
- that.codeReader.decodeFromInputVideoDeviceContinuously(
- that.deviceId,
- 'video',
- (result, err) => {
- that.scanResult = ''
- if (result) {
- that.codeReader.reset()
- this.$toast('result:' + result.text)
- }
- if (err && !err) {
- that.codeReader.reset()
- this.$toast('err:' + JSON.stringify(err))
- }
- }
- )
- },
- },
- }
- </script>
-
- <style lang="less" scoped>
- .container {
- position: relative;
- height: 100vh;
- width: 100%;
- background-color: rgba(0, 0, 0, 0.1);
- }
- .scan-video {
- height: calc(100% - 4px);
- width: 100%;
- object-fit: cover;
- }
- </style>
注意:video 我这边在安卓app中调用的时候,因为照相机视频流还未返回,会出现
这种情况,可以给video添加poster
此外还有一个问题,如果识别结束,跳转到下个页面,在下个页面如果使用倒计时返回,则不能获取到相机视频流,如果手动触发按钮返回,则可以获取到相机视频流,暂未找到原因
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。