html部分:
页面需要一个容器来接收扫描数据
注意:安卓版PDA扫描不同于win系统版本,安卓版本获取扫描数据时并不是keyCode按键依次获取,而是一次性给出扫描的数据
js部分:
扫描枪扫描后,需要有聚焦的承载扫描数据的容器。在手机上或者android版本上会有虚拟键盘的弹出。就需要在scan页面时承载容器要时刻聚焦,还需要在聚焦时不弹出虚拟键盘
data() {
return {
// 扫描枪
code: '',
lastTime: '',
nextTime: '',
lastCode: '',
nextCode: '',
scanCodeValue: '', // 扫描枪获取到的数据
idString: '', // 接受扫描数据textarea的id
}
},
created() {
// 抓取扫描枪数据
document.onkeydown = (e) => {
if (window.event) {
// IE
this.nextCode = e.keyCode
} else if (e.which) {
// Netscape/Firefox/Opera
this.nextCode = e.which
}
if (e.which === 229) { // 安卓版PDA扫描枪扫描完后完成键的keycode=229
// 其他类型可根据keycode值来确认哪一个是完成值
console.log('扫码结束。')
setTimeout(() => {
this.code = this.scanCodeValue
// 扫码枪的速度很快,手动输入的时间不会让code的长度大于2,所以这里不会对扫码枪有效
if (this.code.length < 3) return
console.info('扫码得到的数据scanCodeValue ' + this.code)
// 获取到扫码枪输入的内容,做别的操作
console.info('获取到扫码枪输入的内容,做别的操作')
this.lastCode = ''
this.lastTime = ''
this.scanCodeValue = ''
})
return
}
// 扫码操作,每次完成后会清空上一次的本地暂存信息,用于防止干扰
this.nextTime = new Date().getTime()
if (!this.lastTime && !this.lastCode) {
this.scanCodeValue = ''
this.code = ''
console.log('扫码开始---', this.code)
}
if (this.lastCode && this.lastTime && this.nextTime - this.lastTime > 500) {
// 当扫码前有keypress事件时,防止首字缺失
this.code = this.scanCodeValue
console.log('防止首字缺失---', this.code)
} else if (this.lastCode && this.lastTime) {
this.code = this.scanCodeValue
// 屏蔽不同版本的扫描枪结尾的特殊操作符
let thisCode = this.code
thisCode += '' // 将键盘特殊键转为字符串,防止后续操作异常
thisCode = thisCode.toLowerCase()
if (thisCode.indexOf('controlshiftj') !== -1 ||
thisCode.indexOf('shift') !== -1) {
event.returnValue = false
}
console.log('扫码中---', this.code)
}
this.lastCode = this.nextCode
this.lastTime = this.nextTime
},
mounted () {
// 如果首次进入就需要扫描的话,需要进入后textarea聚焦,如果首次不需要scan,此处可省略
// scan overflow 首次进入页面时接受扫描数据textarea获取焦点
this.idString = this.$refs.scanLocation.$attrs.id
this.getFocus(this.idString)
},
methods: {
// 扫描枪事件 接受扫描枪数据的textarea获取焦点
getFocus (idString) {
// 获取焦点时虚拟键盘不允许弹出
let inp = document.getElementById(idString)
// 1,2,3顺序不可乱
inp.setAttribute('readonly', true) // 1添加只读属性
inp.focus() // 2聚焦 用于接受扫描枪数据
setTimeout(() => {
inp.removeAttribute('readonly') // 3聚焦后用于接受扫描枪数据
})
},
// 接受扫描枪数据的textarea失去焦点时强制获取焦点
onBlur (idString) {
this.getFocus(idString)
},
}



