| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107 |
- <template>
- <view>
- <view>监听到的内容:{{ inputString }}</view>
- <view class="">
- --------------------分割线-----------------------------
- </view>
- <view class="">
- {{text}}
- </view>
- <view class="">
- --------------------分割线-----------------------------
- </view>
- <view class="">
- {{aaa}}
- </view>
- <keyboard-listener v-if="outscan" @keyup="monitorKeyboard"></keyboard-listener>
- </view>
- </template>
- <script>
- import keyboardListener from 'uniapp-keyboard-listener';
- export default {
- components: {keyboardListener},
- data() {
- return {
- inputString: '',
- inputCache: '',
- text:'',
- aaa:'',
- outscan:false,
- keyArr:[],
- nvalue:''
- };
- },
- methods: {
- monitorKeyboard(e) {
- console.log(e)
- if (e.key.length == 1) { // 字母和数字的长度都是1,所以只要字母和数字的按键,适配不同的设备
- this.keyArr.push(e.key)
- } else if (e.key == 'Enter') { // 监听到回车
- let newArr = [];
- this.nvalue = '';
- // 条码中可能会有大写字母和未定义的按键,所以要过滤出来
- newArr = this.keyArr.filter(item => item != 'Shift' && item != 'Enter' && item != 'Unidentified')
- this.nvalue = newArr.join("")
- console.log("回车", newArr, this.nvalue);
- // if (this.nvalue) {
- // this.search(this.nvalue)
- // }
- this.keyArr = [];
- }
- },
- onConfirm(text) {
- // alert(JSON.stringify(text))
- console.log('拿到的text', text);
- // 此处写我们自己的逻辑
- this.text = text;
- },
- keypress(e) {
- console.log(e)
- this.aaa = JSON.stringify(e);
- if (e.keyCode === 66 || e.key === 'Enter') {
- this.inputString = this.inputCache;
- this.onConfirm(this.inputString);
- this.inputCache = '';
- } else {
- if (e.key !== 'Shift') {
- this.inputCache += e.key;
- }
- }
- }
- },
- onLoad() {
- this.outscan=true
- // uni.onkeyup(res=>{
- // console.log(res)
- // })
- // #ifdef APP-PLUS
- // plus.key.addEventListener("keyup", this.keypress);
- // #endif
- // #ifdef H5
- document.addEventListener("keyup", this.keypress);
- // #endif
- },
- beforeDestroy() {
- // #ifdef APP-PLUS
- plus.key.removeEventListener("keyup", this.keypress);
- // #endif
- // #ifdef H5
- document.removeEventListener("keyup", this.keypress);
- // #endif
- },
- deactivated() {
- // #ifdef APP-PLUS
- plus.key.removeEventListener("keyup", this.keypress);
- // #endif
- // #ifdef H5
- document.removeEventListener("keyup", this.keypress);
- // #endif
- }
- };
- </script>
|