index.vue 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. <template>
  2. <view>
  3. <view>监听到的内容:{{ inputString }}</view>
  4. <view class="">
  5. --------------------分割线-----------------------------
  6. </view>
  7. <view class="">
  8. {{text}}
  9. </view>
  10. <view class="">
  11. --------------------分割线-----------------------------
  12. </view>
  13. <view class="">
  14. {{aaa}}
  15. </view>
  16. <keyboard-listener v-if="outscan" @keyup="monitorKeyboard"></keyboard-listener>
  17. </view>
  18. </template>
  19. <script>
  20. import keyboardListener from 'uniapp-keyboard-listener';
  21. export default {
  22. components: {keyboardListener},
  23. data() {
  24. return {
  25. inputString: '',
  26. inputCache: '',
  27. text:'',
  28. aaa:'',
  29. outscan:false,
  30. keyArr:[],
  31. nvalue:''
  32. };
  33. },
  34. methods: {
  35. monitorKeyboard(e) {
  36. console.log(e)
  37. if (e.key.length == 1) { // 字母和数字的长度都是1,所以只要字母和数字的按键,适配不同的设备
  38. this.keyArr.push(e.key)
  39. } else if (e.key == 'Enter') { // 监听到回车
  40. let newArr = [];
  41. this.nvalue = '';
  42. // 条码中可能会有大写字母和未定义的按键,所以要过滤出来
  43. newArr = this.keyArr.filter(item => item != 'Shift' && item != 'Enter' && item != 'Unidentified')
  44. this.nvalue = newArr.join("")
  45. console.log("回车", newArr, this.nvalue);
  46. // if (this.nvalue) {
  47. // this.search(this.nvalue)
  48. // }
  49. this.keyArr = [];
  50. }
  51. },
  52. onConfirm(text) {
  53. // alert(JSON.stringify(text))
  54. console.log('拿到的text', text);
  55. // 此处写我们自己的逻辑
  56. this.text = text;
  57. },
  58. keypress(e) {
  59. console.log(e)
  60. this.aaa = JSON.stringify(e);
  61. if (e.keyCode === 66 || e.key === 'Enter') {
  62. this.inputString = this.inputCache;
  63. this.onConfirm(this.inputString);
  64. this.inputCache = '';
  65. } else {
  66. if (e.key !== 'Shift') {
  67. this.inputCache += e.key;
  68. }
  69. }
  70. }
  71. },
  72. onLoad() {
  73. this.outscan=true
  74. // uni.onkeyup(res=>{
  75. // console.log(res)
  76. // })
  77. // #ifdef APP-PLUS
  78. // plus.key.addEventListener("keyup", this.keypress);
  79. // #endif
  80. // #ifdef H5
  81. document.addEventListener("keyup", this.keypress);
  82. // #endif
  83. },
  84. beforeDestroy() {
  85. // #ifdef APP-PLUS
  86. plus.key.removeEventListener("keyup", this.keypress);
  87. // #endif
  88. // #ifdef H5
  89. document.removeEventListener("keyup", this.keypress);
  90. // #endif
  91. },
  92. deactivated() {
  93. // #ifdef APP-PLUS
  94. plus.key.removeEventListener("keyup", this.keypress);
  95. // #endif
  96. // #ifdef H5
  97. document.removeEventListener("keyup", this.keypress);
  98. // #endif
  99. }
  100. };
  101. </script>