扫码枪相当于键盘输入设备,输入一连串数字后加一个enter键。
但在实际开发中需要区分是扫描枪输入还是键盘用户输入,区别在于扫码枪输入很快
1.获取扫码枪扫码的数据
// 监听扫码
window.document.onkeypress = (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,所以这里不会对扫码枪有效
this.parseQRCode(this.code); // 获取到扫码枪输入的内容,做别的操作
this.lastCode = "";
this.lastTime = "";
return;
}
this.nextTime = new Date().getTime();
if (
this.lastCode &&
this.lastTime &&
this.nextTime - this.lastTime > 500
) {
// 当扫码前有keypress事件时,防止首字缺失
this.code = e.key;
} else if (this.lastCode && this.lastTime) {
this.code += e.key;
}
this.lastCode = this.nextCode;
this.lastTime = this.nextTime;
};
this.parseQRCode这个函数是获取到扫码的数据进行处理,我这边的逻辑是要拿到他请求后台数据拿到条形码
parseQRCode(code) {