useEventListener.js 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. import { ref } from 'vue';
  2. import { onShow, onHide, onUnload, onLoad } from '@dcloudio/uni-app'
  3. import { useGlobalEvent } from '@/utils/utils.js'
  4. /**
  5. * 基于 Vue3 组合式的全局扫码事件监听器
  6. * 在页面 onShow 时注册,在 onHide/onUnload 时自动注销
  7. * @param {(event: any) => void} onEvent 回调,参数为原始事件对象(包含 e.barcode)
  8. * @returns {{ stop: () => void }} 返回手动停止方法
  9. */
  10. export function useEventListener(onEvent, isOnShow = false) {
  11. if (typeof onEvent !== 'function') {
  12. throw new Error('useEventListener 需要传入函数类型的回调');
  13. }
  14. const cleanupRef = ref(null);
  15. const register = () => {
  16. // #ifdef APP-PLUS
  17. if (!cleanupRef.value) {
  18. cleanupRef.value = useGlobalEvent(onEvent);
  19. }
  20. // #endif
  21. };
  22. const unregister = () => {
  23. if (cleanupRef.value) {
  24. cleanupRef.value();
  25. cleanupRef.value = null;
  26. }
  27. };
  28. !isOnShow && onShow(register);
  29. onHide(unregister);
  30. onUnload(unregister);
  31. return {
  32. unregister: unregister,
  33. register: register
  34. };
  35. }