如何在不刷新页面的情况下同步数据库更新后的配置状态
解决不刷新页面同步数据库与UI的问题
核心问题分析
当前代码存在两个关键问题:
- 状态更新时机错误:在设备配置请求发送前就更新了store状态,若请求失败会导致store与实际设备状态不一致;
- 响应式更新可能失效:直接修改
_currentRoom的属性,若对象未被正确追踪响应式,UI无法实时感知变化。
具体修复步骤
1. 调整状态更新顺序
将store状态更新逻辑移至设备配置请求成功后,确保只有操作成功才标记为已配置:
// .ts 文件修改后的 sendConfiguration 方法 public async sendConfiguration() { try { this.displayOverlayConfigurationMessage(true); const configurationDeviceService = ConfigurationDeviceFactory.create( this.deviceModuleStore.currentNetworkAddress, new EncryptDecryptValues() ); // 优先完成设备配置发送 await configurationDeviceService.send( this.deviceModuleStore.currentPassword, this.roomModuleStore.currentRoom ); await this.disconnectFromDevice(); // 操作成功后再更新数据库与store await this.roomModuleStore.setIsConfigured(true); this.displayOverlayConfigurationMessage(false); Notifier.showInfo( this.$t('pages.projects.project.room.configuration.configurationSent') as string ); } catch (error) { // 失败时回滚状态 await this.roomModuleStore.setIsConfigured(false); this.displayOverlayConfigurationMessage(false); // 补充错误提示逻辑 Notifier.showError(this.$t('pages.projects.project.room.configuration.failure') as string); } }
2. 优化Store的响应式更新
修改Store的Mutation与Action,通过替换整个_currentRoom对象确保响应式追踪(避免直接修改属性可能导致的更新失效):
// roomModule.ts 文件修改 @Mutation private setCurrentRoom(room: Room) { // 替换整个对象,确保响应式系统感知变化 this._currentRoom = room; } @Action({ rawError: true }) public async setIsConfigured(value: boolean): Promise<boolean> { const updatedRoom = _.cloneDeep(this._currentRoom); updatedRoom.isConfigured = value; // 先完成数据库持久化 await this._storageService.persist(Room, updatedRoom); // 更新store中的状态 this.commit('setCurrentRoom', updatedRoom); return value; }
3. 确保UI绑定Store状态
在Vue组件中通过计算属性绑定Store中的响应式状态,而非直接读取数据库:
<template> <!-- 示例:根据配置状态显示不同内容 --> <div v-if="isConfigured">已完成配置</div> <div v-else>未配置</div> <!-- 原按钮代码 --> <div class="q-pa-lg c-btn__action"> <q-btn :ripple="false" size="md" color="primary" class="full-width" text-color="white" @click="sendConfiguration" :label="$t('pages.projects.project.template.loadingConfiguration')" :disable="!isConnected || !allPeripheralsIdentified || isConfigured" data-cy="send-configuration-btn" /> </div> </template> <script setup lang="ts"> import { computed } from 'vue'; import { useRoomModuleStore } from '@/stores/roomModule'; const roomStore = useRoomModuleStore(); // 绑定Store中的响应式状态 const isConfigured = computed(() => roomStore._currentRoom.isConfigured); // 其他变量如isConnected、allPeripheralsIdentified按原有逻辑引入 </script>
额外检查点
- 确认
_storageService.persist方法确实完成了数据库的异步写入,且无异常; - 若项目使用Pinia,确保
_currentRoom是在Store的state中定义的响应式对象; - 避免在UI中直接读取数据库原始数据,统一通过Store获取状态。
内容的提问来源于stack exchange,提问作者Priyanka Rajendran
相关产品推荐
相关产品推荐

