当前位置:   article > 正文

vue2项目通过ZXing.js实现扫描二维码功能

zxing.js

1.安装依赖包

npm install @zxing/library -S
  • 1

2.项目中使用

<template>
	<video :id="vId" autoplay style="width: 100%; height: 500px;"></video>
</template>
  • 1
  • 2
  • 3
<script>
import { BrowserMultiFormatReader } from '@zxing/library';

export default {
	data() {
		return {
			vId: 'codeVideo',
			codeReader: new BrowserMultiFormatReader(),
	    };
	},
	created() {
		this.scanCode();
	},
	methods: {
		scanCode() {
			this.codeReader.getVideoInputDevices().then((videoInputDevices) => {
				const leng = videoInputDevices.length;
				if (!leng) {
					return console.error( '找不到摄像头');	
				}
				const deviceId = videoInputDevices[leng - 1].deviceId;
				this.codeReader.decodeFromInputVideoDeviceContinuously(deviceId, this.vId, (result, err) => {
					if (result) {
						console.error(result.text);
					}
					if (err) {
						console.error(err);
					}
				});
			}).catch(err => {
        		console.error(err);
      		}).finally(() => {
       	    	this.codeReader.reset(); // 销毁扫描
        	});
		},
	},
}
</script>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38

3.注意事项

摄像头必须在 https 下才能获取到,在 vue.config.js 文件中添加以下代码:

module.exports = {
	devServer: {
		https: true, // 添加这一行代码
	},
};
  • 1
  • 2
  • 3
  • 4
  • 5

然后运行 npm run serve 重启项目

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:【wpsshop博客】
推荐阅读
  

闽ICP备14008679号