vue外接扫码枪如何实现
原理
- 扫码枪读取数据会触发键盘事件,所以可以通过监听keydown事件获取数据;
- 数据读取完毕会触发enter键,可以以此判断扫码结束;
- 由于扫码枪触发键盘事件耗时极少,可以通过时间间隔判断是手动输入或是扫码;
- 此处直接对监听数据进行处理,也可使用input框读取数据进行处理;
代码实现
<script lang="ts">
import { onMounted, onUnmounted, reactive, toRefs } from 'vue';
import { message, Input } from 'ant-design-vue';
export default {
components: { Input },
setup(props, { emit }) {
const state = reactive({
instantCode: [],
lastTime: undefined,
nextTime: undefined,
lastCode: '',
nextCode: '',
});
onMounted(() => {
window.onkeydown = (e) => {
watchKeyDown(e);
};
});
function watchKeyDown(e) {
if (window.event) {
state.nextCode = e.key;
} else if (e.which) {
state.nextCode = e.which;
}
if (e.keyCode === 13) {
if (state.instantCode.length < 3) return;
parseQRCode(state.instantCode);
state.lastCode = '';
state.lastTime = '';
return;
}
state.nextTime = new Date().getTime();
if (!state.lastTime && !state.lastCode) {
state.instantCode = [];
state.instantCode.push(e.key);
}
if (state.lastCode && state.lastTime && state.nextTime - state.lastTime > 30) {
state.instantCode = [];
state.instantCode.push(e.key);
} else if (state.lastCode && state.lastTime) {
state.instantCode.push(e.key);
}
state.lastCode = state.nextCode;
state.lastTime = state.nextTime;
}
function parseQRCode(code) {
}
}
onUnmounted(() => {
window.onkeydown = null;
});
return {
...toRefs(state),
};
},
};
</script>