Files
2026-06-02 15:28:25 +08:00

93 lines
2.0 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* uni-app 默认扫码实现
* 使用 uni.scanCode API(安卓设备)
*
* 注意:uni.scanCode 是一次性扫码,每次调用都会弹出扫码界面
* 不支持持续扫描,因此 startScan() 每次都会弹出新界面
*/
class ScanUniappImpl {
constructor() {
this._callback = null
this._isScanning = false
}
/**
* 初始化(uni.scanCode 无需特殊初始化)
*/
init() {
console.log('[Scan-Uniapp] 初始化完成(使用 uni.scanCode')
}
/**
* 注册扫码结果回调
* @param {Function} callback - (codeStr: string) => void
*/
register(callback) {
this._callback = callback
}
/**
* 注销监听(页面卸载时调用)
*/
unregister() {
this._callback = null
}
/**
* 开始扫描(调用 uni.scanCode
* 注意:每次调用都会弹出扫码界面
*/
startScan() {
if (this._isScanning) return
this._isScanning = true
const self = this
uni.scanCode({
success: (res) => {
self._isScanning = false
console.log('[Scan-Uniapp] 扫码结果:', res.result)
if (self._callback) {
self._callback(res.result)
}
},
fail: (err) => {
self._isScanning = false
console.error('[Scan-Uniapp] 扫码失败:', err)
// 用户取消不算错误,不显示 toast
if (err.errMsg && err.errMsg.indexOf('cancel') === -1) {
uni.showToast({ title: '扫码失败', icon: 'none' })
}
},
complete: () => {
self._isScanning = false
}
})
}
/**
* 停止扫描(uni.scanCode 无法中途停止,此方法仅重置状态)
*/
stopScan() {
this._isScanning = false
}
/**
* 是否正在扫描
* 注意:uni.scanCode 是异步的,调用后界面会切换,此方法主要用于防止重复调用
*/
isScanning() {
return this._isScanning
}
/**
* 完全销毁(应用退出时调用)
*/
destroy() {
this.unregister()
this._isScanning = false
}
}
export default ScanUniappImpl