vue实现扫码枪
Vue 实现扫码枪功能
监听键盘输入
扫码枪通常模拟键盘输入,可通过监听键盘事件捕获扫描内容。在Vue组件中,添加keydown或keypress事件监听,记录连续输入的字符。
<template>
<div @keydown="handleKeyDown" tabindex="0">
<p>扫描结果: {{ scanResult }}</p>
</div>
</template>
<script>
export default {
data() {
return {
scanResult: '',
scanBuffer: '',
lastKeyTime: 0
};
},
methods: {
handleKeyDown(event) {
const currentTime = Date.now();
if (currentTime - this.lastKeyTime > 50) {
this.scanBuffer = '';
}
this.lastKeyTime = currentTime;
if (event.key === 'Enter') {
this.scanResult = this.scanBuffer;
this.scanBuffer = '';
} else {
this.scanBuffer += event.key;
}
}
},
mounted() {
this.$el.focus();
}
};
</script>
使用第三方库
对于更复杂的场景,可使用专门处理扫码枪输入的库如quagga或html5-qrcode。
安装html5-qrcode:
npm install html5-qrcode
在Vue中使用:
<template>
<div>
<div id="qr-reader" style="width: 300px"></div>
<p>扫描结果: {{ scanResult }}</p>
</div>
</template>
<script>
import { Html5Qrcode } from 'html5-qrcode';
export default {
data() {
return {
scanResult: '',
html5QrCode: null
};
},
mounted() {
this.html5QrCode = new Html5Qrcode("qr-reader");
this.html5QrCode.start(
{ facingMode: "environment" },
{ fps: 10 },
(decodedText) => {
this.scanResult = decodedText;
},
(errorMessage) => {
console.error(errorMessage);
}
);
},
beforeDestroy() {
this.html5QrCode.stop().then(() => {
this.html5QrCode.clear();
});
}
};
</script>
优化输入处理
对于快速连续输入,可设置超时机制自动确认扫描完成,无需等待回车键。
methods: {
handleKeyDown(event) {
clearTimeout(this.scanTimer);
this.scanBuffer += event.key;
this.scanTimer = setTimeout(() => {
if (this.scanBuffer.length > 3) {
this.scanResult = this.scanBuffer;
this.scanBuffer = '';
}
}, 100);
}
}
注意事项
- 确保监听元素可获得焦点(如添加
tabindex属性) - 移动端需处理相机权限问题
- 生产环境建议添加扫描成功的声音反馈
- 对于高频率扫描场景,考虑防抖处理







