扫描枪模拟的是键盘输入事件,所以我们可以监听键盘按下事件(window.document.onkeypress)来实现相关需求。
可以在created/mounted中添加事件。
具体方法:
// 监听扫描
addScanMonitor() {
window.document.onkeypress = e => {
console.log(e)
if (window.event) { // IE
this.nextCode = e.keyCode
} else if (e.which) { // Netscape/Firefox/Opera
this.nextCode = e.which
}
if (e.which === 13) { // 键盘回车事件
if (this.code.length < 3) return // 扫码枪的速度很快,手动输入的时间不会让code的长度大于2,所以这里不会对扫码枪有效
console.log('扫码结束,条形码:', this.code)
this.scanningForm.scanCode = this.code
this.lastCode = ''
this.lastTime = ''
this.handleSubmitScanning()
return
}
this.nextTime = new Date().getTime()
if (!this.lastTime && !this.lastCode) {
this.code = '' // 清空上次的条形码
// 继续扫描一下条前关闭弹窗
this.handleCloseTipsVisible()
this.code += e.key
console.log('扫码开始---', this.code)
}
if (this.lastCode && this.lastTime && this.nextTime - this.lastTime > 500) { // 当扫码前有keypress事件时,防止首字缺失
this.code = e.key
console.log('防止首字缺失。。。', this.code)
} else if (this.lastCode && this.lastTime) {
this.code += e.key
console.log('扫码中。。。', this.code)
}
this.lastCode = this.nextCode
this.lastTime = this.nextTime
}
}