扫条形码:
扫二维码:
zxing
下载:
npm install @zxing/library --save
扫码组件内容:
<template><div><video id="video-1"></video></div></template><script >import {BrowserMultiFormatReader,ChecksumException,FormatException} from '@zxing/library'export default {name: 'Scan',data () {return {codeReader: new BrowserMultiFormatReader(),videoInputDevices: [],currentVideoInputDevice: {},decodeResult: undefined}},methods: {async openScan () {const _this = this_this.codeReader.getVideoInputDevices() // 老版本listVideoInputDevices().then((videoInputDevices) => {console.log(videoInputDevices, 'videoInputDevices')if (videoInputDevices && videoInputDevices.length) {if (videoInputDevices.length > 1) {videoInputDevices.reverse()} // 防止先唤出前摄像头_this.videoInputDevices = videoInputDevices_this.currentVideoInputDevice = videoInputDevices[0]}}).catch(() => {})},decodeFromInputVideo () {const _this = this_this.codeReader.reset()// 多次_this.codeReader.decodeFromVideoDevice(_this.currentVideoInputDevice.deviceId,'video-1',(result, err) => {if (result) {_this.decodeResult = result}if (err) {if (err instanceof ChecksumException) {console.log("A code was found, but it's read value was not valid.")}if (err instanceof FormatException) {console.log('A code was found, but it was in a invalid format.')}}})},successDecode () {const _this = thisalert(_this.decodeResult.text)}},watch: {currentVideoInputDevice: function () {this.decodeFromInputVideo()},decodeResult: function () {this.successDecode()}},mounted: function () {this.openScan()},unmounted: function () {this.codeReader.reset() // 关闭摄像头}}</script>
这个用来扫条形码, 感觉不是很快,我们设备上的条形码扫不出来,应该是条码太小导致的。
扫二维码倒是很快。
vue-barcode-reader
github:/olefirenko/vue-barcode-reader
npm install vue-barcode-reader --save
import {StreamBarcodeReader } from "vue-barcode-reader";
<StreamBarcodeReader @decode="onDecode" @loaded="onLoaded"></StreamBarcodeReader>
onDecode (val) {alert(val, 'onDecode')},onLoaded (val) {alert(val, 'onLoaded')}