扫码枪的工作原理和键盘输入事件一样:
方法一、在created钩子函数里面监听键盘输入的事件获取扫码枪输入的值:
var b = "";
var _this = this;
document.onkeydown = function() {
if (event.keyCode != 13) {
var bizCode = String.fromCharCode(event.keyCode);
if (event.keyCode >= 48 && event.keyCode <= 122) {
b = b + bizCode;
}
} else {
b = "";
}
_this.msg = b;
};
方法二:通过输入框聚焦事件获取输入的值:
<el-input ref="scanInput" v-model="handoverSeq" @blur="inputblur()"></el-input>
不过大部分的扫码枪需求就是输入框是不能在页面展示的,所以就要隐藏掉,但是隐藏的话就会导致聚焦事件失效,推荐使用z-index=-1可以解决;
// 初始获取焦点
keyPress () {
// nextTik 针对DOM 没有渲染出现Undefined问题
this.$nextTick(() => {
this.$refs.scanInput.focus()
})
},
// 失去焦点
inputblur () {
let that = this
// FireFox 和 IE 失去焦点,blur直接执行focus 不会生效,加个延时
setTimeout(() => {
that.$refs.scanInput.focus()
}, 10)
},
最后通过防抖监听输入间隔超过1000毫秒后就用扫码枪的数据调用接口去获取数据:
created() {
this.$nextTick(() => {
this.$watch(
"handoverSeq",
debounce(newQuery => {
if (this.handoverSeq) {
console.log("扫码获取的交接流水号",this.handoverSeq)
this.sendHandoverReceive(newQuery);//接口调用方法
this.handoverSeq = "";
}
}, 1000)
);
});
},
在文件utils.js中做防抖函数暴露使用:
//防抖处理
export function debounce(func, delay) {
let timer
return function (...args) {
if (timer) {
clearTimeout(timer)
}
timer = setTimeout(() => {
func.apply(this, args)
}, delay)
}
}