话不多说直接上代码 ,自己网上搜了半天然后拼拼凑凑搞出来的成功版本,还是萌新,有错轻喷
<template>
<view class="content">
<input
id="pdaInput"
class="input"
type="password"
ref="searchInput"
v-model="scanCodeValue"
:placeholder="placeholder"
:focus="focusState"
@focus="focusFn"
@blur="focusState = false"
/>
<input
class="input"
type="text"
:value="scanCodeValue"
:placeholder="placeholder2"
/>
<button @click="clear">clear</button>
</view>
</template>
<script>
export default {
data () {
return {
scanCodeValue: '',
placeholder: '请扫码...',
placeholder2: 's',
focusState: false
}
},
created () {
// 抓取扫描枪数据
document.onkeydown = (e) => {
this.startScan()
}
},
watch: {
scanCodeValue (value) {
if (!!value) {
document.onkeydown = null
} else {
this.placeholder = '扫码失败,请重新扫码...'
}
}
},
destroyed () {
//取消键盘监听事件
document.onkeydown = null
},
methods: {
focusFn () {
// 聚焦后事件
},
clear () {
this.scanCodeValue = ''
document.onkeydown = (e) => {
this.startScan()
}
},
startScan () {
this.$nextTick(() => {
this.focusState = true
})
// 自动获取input输入框焦点
if (e.which === 13) { // 安卓版PDA扫描枪扫描完后完成键的keycode=229
// 其他类型可根据keycode值来确认哪一个是完成值,我的是13
setTimeout(() => {
if (this.scanCodeValue.length < 3) return
this.scanCodeValue = ''
}, 500)
return
}
}
}
}
</script>
<style>
.content {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
.input {
margin: 50px auto 0;
padding: 3px;
height: 30px;
width: 200px;
border: black 1px solid;
border-radius: 2px;
}
</style>
最终效果如下,进入页面直接点pda上的扫描按钮对准条形码就能将数值扫进输入框,对应的绑定事件就可以根据业务需求来修改