vue外接扫码枪如何实现
【代码】vue外接扫码枪如何实现。
·
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 }) {
// 扫码枪连续触发很快,,手动输入连续敲击也会大于30
const state = reactive({
instantCode: [], //实时的值
lastTime: undefined,
nextTime: undefined,
lastCode: '',
nextCode: '',
});
onMounted(() => {
// console.log('开始监测');
window.onkeydown = (e) => {
watchKeyDown(e);
};
});
//监听键盘按下事件(包括扫码枪触发的事件)并进行处理
function watchKeyDown(e) {
// console.log(e);
if (window.event) {
// IE
state.nextCode = e.key;
} else if (e.which) {
// Netscape/Firefox/Opera
state.nextCode = e.which;
}
if (e.keyCode === 13) {
// console.log('keyCode==13', state.instantCode);
// 键盘回车事件
if (state.instantCode.length < 3) return; // 扫码枪的速度很快,手动输入的时间不会让code的长度大于2,所以这里不会对扫码枪有效
// console.log("扫码结束。");
// console.log("二维码:", state.instantCode);
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);
// console.log("扫码开始---", state.instantCode);
}
if (state.lastCode && state.lastTime && state.nextTime - state.lastTime > 30) {
state.instantCode = []; // 清空上次的 首次
// 相隔时间大于30 说明之前的不是扫码枪的
// 当扫码前有keydown事件时,防止首字缺失
state.instantCode.push(e.key);
// console.log("防止首字缺失。。。", state.instantCode);
} else if (state.lastCode && state.lastTime) {
state.instantCode.push(e.key);
// console.log("扫码中。。。", state.instantCode);
}
state.lastCode = state.nextCode;
state.lastTime = state.nextTime;
}
function parseQRCode(code) {
//数据处理
}
// console.log('扫码结束===》', code.join(''));
}
onUnmounted(() => {
window.onkeydown = null;
});
return {
...toRefs(state),
};
},
};
</script>
更多推荐
已为社区贡献1条内容
所有评论(0)