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