uniapp监听扫码枪键盘事件|无输入框式监听
生活随笔
收集整理的这篇文章主要介绍了
uniapp监听扫码枪键盘事件|无输入框式监听
小编觉得挺不错的,现在分享给大家,帮大家做个参考.
一般的扫码枪通过USB或蓝牙连接手机或电脑,充当的是一个外接设备。当扫码后,扫码枪会自动识别内容,然后向连接的电脑或手机发送键盘事件keydown或keyup。
input输入框式
如果页面上有input输入框就很简单,直接聚焦input,然后扫码,input框会自动填充内容,并自动产生回车事件,代码只需处理回车事件即可。
<template><input v-model="inputString" @confirm="onConfirm" /> </template><script setup> import { ref } from "vue" const inputString = ref("") const onConfirm = () => {console.log('输入的值为', inputString.value) } </script>以上代码,h5、App都适用。
无输入框式
没有input框时,就需要监听页面的键盘事件。h5可以使用document.keyup来监听,但是app里没有document,只能使用plus.key来监听。处理逻辑一样,只是监听方式不一样。
同时兼容H5和APP的用法
<template><view>监听到的内容:{{inputString}}</view> </template><script setup> import { ref } from "vue" import { onLoad, onShow, onHide, onBackPress, onUnload } from "@dcloudio/uni-app"; const inputString = ref('') const keyCodeCache = ref([]) const inputCache = ref('') const onConfirm = (code)=>{console.log('拿到的code', code);// 此处写我们自己的逻辑 } const keypress = (e) => {if (e.keyCode === 66 || e.key =='Enter') {inputString.value = inputCache.value;onConfirm(inputString.value)inputCache.value = '';} else {inputCache.value += e.key} }onLoad((options) => {// #ifdef APP-PLUSplus.key.addEventListener("keyup", keypress);// #endif // #ifdef H5document.addEventListener("keyup", keypress);// #endif }) onUnload(()=>{// #ifdef APP-PLUSplus.key.removeEventListener("keyup", keypress);// #endif// #ifdef H5document.removeEventListener("keyup", keypress);// #endif }) onHide(()=>{// #ifdef APP-PLUSplus.key.removeEventListener("keyup", keypress);// #endif// #ifdef H5document.removeEventListener("keyup", keypress);// #endif }) onBackPress(()=>{// #ifdef APP-PLUSplus.key.removeEventListener("keyup", keypress);// #endif// #ifdef H5document.removeEventListener("keyup", keypress);// #endif }) </script>实际运行时,可能出现键盘的key和keyCode不兼容问题,不同的设备对应的键盘keyCode可能也不一样,首先要设置扫码枪的键盘模式,然后做一层转换。
下面的扫码枪设置为US Keyboard的转换部分逻辑
总结
以上是生活随笔为你收集整理的uniapp监听扫码枪键盘事件|无输入框式监听的全部内容,希望文章能够帮你解决所遇到的问题。
- 上一篇: PROE基本操作1(查看组件尺寸)
- 下一篇: 国内邮箱排名VIP邮箱哪个好?VIP邮箱