# 条码扫描模块使用指南 ## 概述 优化后的条码扫描模块增加了内存泄露防护、自动清理机制和更好的错误处理。 ## 主要优化 1. **内存泄露防护**:自动清理已销毁页面的回调函数 2. **重复注册检测**:防止同一页面多次注册导致的问题 3. **错误处理**:增加了全面的错误处理和日志记录 4. **页面生命周期管理**:使用 WeakRef 自动检测页面销毁 5. **状态管理**:更好的全局监听器状态管理 ## 使用方法 ### 1. 页面中注册扫描监听 ```javascript // 在页面的 onLoad 或 onShow 中注册 import { useGlobalEvent, cleanupOnPageUnload } from '@/utils/useBarcodeModule' export default { data() { return { cleanupFunction: null } }, onLoad() { // 注册扫描监听 this.cleanupFunction = useGlobalEvent((scanResult) => { console.log('扫描结果:', scanResult) // 处理扫描结果 }) }, onUnload() { // 页面卸载时清理回调 - 重要! if (this.cleanupFunction) { this.cleanupFunction() } // 或者使用便捷方法 cleanupOnPageUnload() } } ``` ### 2. 在 App.vue 中管理全局状态 ```javascript // App.vue import { updateActivePageOnShow, useGlobalEventRemove } from '@/utils/useBarcodeModule' export default { onShow() { // 更新活跃页面,触发自动清理 updateActivePageOnShow() }, onHide() { // 应用隐藏时可以选择性清理 // useGlobalEventRemove() // 如果需要完全清理 } } ``` ### 3. 使用 Composition API (Vue 3) ```javascript import { onMounted, onUnmounted } from 'vue' import { useGlobalEvent } from '@/utils/useBarcodeModule' export default { setup() { let cleanup = null onMounted(() => { cleanup = useGlobalEvent((scanResult) => { console.log('扫描结果:', scanResult) }) }) onUnmounted(() => { if (cleanup) { cleanup() } }) } } ``` ### 4. 调试和监控 ```javascript import { getRegistryStatus } from '@/utils/useBarcodeModule' // 查看当前注册状态 const status = getRegistryStatus() console.log('当前注册状态:', status) /* 输出示例: { activePagePath: "pages/scan/index", registeredPages: ["pages/scan/index", "pages/home/index"], totalCallbacks: 2, isGlobalListenerInitialized: true } */ ``` ## API 说明 ### useGlobalEvent(onChange) - **参数**: `onChange` - 扫描结果回调函数 - **返回**: 清理函数 - **功能**: 注册当前页面的扫描监听器 ### updateActivePageOnShow() - **功能**: 更新当前活跃页面,触发自动清理 - **调用时机**: 在 App.vue 的 onShow 中调用 ### removePageCallback(pagePath) - **参数**: `pagePath` - 可选,页面路径 - **功能**: 移除指定页面的回调 ### cleanupOnPageUnload() - **功能**: 清理当前页面的回调 - **调用时机**: 在页面的 onUnload 中调用 ### useGlobalEventRemove() - **功能**: 完全移除全局监听器和所有回调 - **调用时机**: 应用退出时或需要重置时 ### getRegistryStatus() - **返回**: 当前注册状态对象 - **功能**: 调试用,查看当前注册状态 ## 最佳实践 1. **始终在页面卸载时清理**:使用返回的清理函数或 `cleanupOnPageUnload()` 2. **在 App.vue 中调用 updateActivePageOnShow()**:确保自动清理机制正常工作 3. **避免在同一页面多次注册**:会有警告提示,但建议避免 4. **使用 getRegistryStatus() 调试**:在开发阶段监控内存使用情况 ## 错误处理 模块包含完善的错误处理: - 页面路径获取失败时的安全处理 - 回调函数执行错误的捕获 - 全局监听器初始化失败的处理 - 详细的警告和错误日志 ## 注意事项 1. **WeakRef 兼容性**:使用了 WeakRef 进行自动清理,确保运行环境支持 2. **条件编译**:部分功能使用了 `#ifdef APP-PLUS` 条件编译 3. **内存监控**:在开发阶段建议使用 `getRegistryStatus()` 监控内存使用情况