This commit is contained in:
hayu 2025-07-31 14:26:52 +08:00
parent f5d7d64199
commit b5958272e2
1 changed files with 46 additions and 31 deletions

View File

@ -132,62 +132,77 @@ export default {
maId: ""
},
codeData: {},
optionList: []
optionList: [],
cameraReady: false
}
},
onLoad(options) {
// 监听OCR识别结果
uni.$on('ocrResult', this.handleOcrResult);
onShow() {
// 更安全的 deviceready 监听
if (window.cordova) {
this.onDeviceReady();
} else {
document.addEventListener('deviceready', this.onDeviceReady, false);
}
},
onUnload() {
// 移除事件监听
uni.$off('ocrResult', this.handleOcrResult);
// 确保相机被停止
this.stopCamera();
beforeDestroy() {
if (this.onDeviceReady) {
document.removeEventListener('deviceready', this.onDeviceReady);
}
},
methods: {
onDeviceReady() {
console.log('Cordova 插件已加载');
this.cameraReady = true;
},
// 检查相机权限
async checkCameraPermission() {
return new Promise((resolve, reject) => {
// 检查插件是否可用
if (!window.cordova || !cordova.plugins?.permissions) {
reject(new Error('权限插件不可用'));
return;
}
const permissions = cordova.plugins.permissions;
permissions.checkPermission(permissions.CAMERA,
permissions.checkPermission(
permissions.CAMERA,
(status) => {
if (status.hasPermission) {
resolve(true); // 已有权限
} else {
// 请求权限
permissions.requestPermission(
permissions.CAMERA,
(status) => {
if (status.hasPermission) {
resolve(true);
} else {
permissions.requestPermission(permissions.CAMERA,
() => resolve(true),
() => reject(new Error('相机权限被拒绝'))
reject(new Error('用户拒绝了相机权限'));
}
},
(error) => reject(new Error('请求权限失败: ' + error))
);
}
},
(error) => reject(new Error('权限检查失败'))
(error) => reject(new Error('检查权限失败: ' + error))
);
});
},
// 打开相机
async openCamera() {
if (!this.cameraReady) {
await uni.showToast({ title: '请等待插件初始化', icon: 'none' });
return;
}
try {
// 检查权限
await this.checkCameraPermission();
// 显示相机界面
this.showCamera = true;
// 等待DOM更新后初始化相机
await this.$nextTick();
await this.$nextTick(); // 确保 UI 更新
await this.initCamera();
} catch (error) {
console.error('打开相机失败:', error);
uni.showToast({
title: error.message || '相机启动失败',
icon: 'none'
});
this.showCamera = false;
console.error('相机启动失败:', error);
}
},