| 1234567891011121314151617181920212223242526272829303132333435363738394041 |
- import { ref } from 'vue';
- import { onShow, onHide, onUnload, onLoad } from '@dcloudio/uni-app'
- import { useGlobalEvent } from '@/utils/utils.js'
- /**
- * 基于 Vue3 组合式的全局扫码事件监听器
- * 在页面 onShow 时注册,在 onHide/onUnload 时自动注销
- * @param {(event: any) => void} onEvent 回调,参数为原始事件对象(包含 e.barcode)
- * @returns {{ stop: () => void }} 返回手动停止方法
- */
- export function useEventListener(onEvent, isOnShow = false) {
- if (typeof onEvent !== 'function') {
- throw new Error('useEventListener 需要传入函数类型的回调');
- }
- const cleanupRef = ref(null);
- const register = () => {
- // #ifdef APP-PLUS
- if (!cleanupRef.value) {
- cleanupRef.value = useGlobalEvent(onEvent);
- }
- // #endif
- };
- const unregister = () => {
- if (cleanupRef.value) {
- cleanupRef.value();
- cleanupRef.value = null;
- }
- };
- !isOnShow && onShow(register);
- onHide(unregister);
- onUnload(unregister);
- return {
- unregister: unregister,
- register: register
- };
- }
|