优化后的条码扫描模块增加了内存泄露防护、自动清理机制和更好的错误处理。
// 在页面的 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()
}
}
// App.vue
import { updateActivePageOnShow, useGlobalEventRemove } from '@/utils/useBarcodeModule'
export default {
onShow() {
// 更新活跃页面,触发自动清理
updateActivePageOnShow()
},
onHide() {
// 应用隐藏时可以选择性清理
// useGlobalEventRemove() // 如果需要完全清理
}
}
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()
}
})
}
}
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
}
*/
onChange - 扫描结果回调函数pagePath - 可选,页面路径cleanupOnPageUnload()模块包含完善的错误处理:
#ifdef APP-PLUS 条件编译getRegistryStatus() 监控内存使用情况