index.vue 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. <template>
  2. <view class="content">
  3. 111
  4. </view>
  5. </template>
  6. <script setup>
  7. import { ref } from "vue";
  8. import {onLoad, onReady, onUnload} from '@dcloudio/uni-app'
  9. // 获取 module
  10. const rfidModule = uni.requireNativePlugin("DeviceModule_RFID");
  11. //渲染完成
  12. onReady(() => {
  13. // #ifdef APP-PLUS
  14. rfidModuleInit()
  15. // #endif
  16. })
  17. //按键操作
  18. const rfidModuleInit = ({keyCode}) => {
  19. uni.showLoading({
  20. title: 'RFID模块加载中...',
  21. mask: true,
  22. });
  23. /**
  24. 手机按键监听事件,可在此编写一些逻辑,如使用按键触发扫描,更多详细信息请查阅uni官方文档
  25. 需要注意:退出界面必须移除监听,否则再进入页面重复注册监听会出现多次触发、回调失效的问题
  26. */
  27. plus.key.addEventListener('keydown', keyListener);
  28. //初始化
  29. setTimeout(() => {
  30. // 使用模块前必须先初始化RDIF模块
  31. let { code } = rfidModule.init();
  32. if (code == 0) {
  33. uni.hideLoading();
  34. } else if (code == -1) {
  35. uni.hideLoading();
  36. uni.showToast({
  37. title: 'RFID模块加载失败',
  38. icon: 'error',
  39. duration: 3000
  40. })
  41. }
  42. }, 400);
  43. }
  44. //按键操作
  45. const keyListener = ({keyCode}) => {
  46. console.log("按键:", keyCode)
  47. if (keyCode === 293 || keyCode === 312) {
  48. if (isScan.value) {
  49. stopScan()
  50. } else {
  51. startScan()
  52. }
  53. }
  54. }
  55. //开始扫描
  56. const isScan = ref(false)
  57. const startScan = async () => {
  58. isScan.value = true
  59. const res = await startScanApi()
  60. console.log(JSON.stringify(res))
  61. console.log(res)
  62. }
  63. //扫描API
  64. const startScanApi = async () => {
  65. return new Promise((resolve) => {
  66. rfidModule.startScan((res) => {
  67. resolve(res)
  68. })
  69. })
  70. }
  71. //停止扫描
  72. const stopScan = () => {
  73. const { code } = rfidModule.stopScan()
  74. if (code === 0) {
  75. isScan.value = false
  76. uni.showToast({
  77. icon: "success",
  78. title: '关闭扫描成功'
  79. })
  80. } else {
  81. uni.showToast({
  82. icon: "error",
  83. title: res.message
  84. })
  85. }
  86. }
  87. //页面卸载
  88. onUnload(()=>{
  89. // #ifdef APP-PLUS
  90. plus.key.removeEventListener('keydown', keyListener)
  91. // 使用完毕必须释放RDIF模块
  92. rfidModule.free();
  93. // #endif
  94. })
  95. </script>