import { DraggablePropsType } from "@/components/Draggable/Draggable"; import { makeAutoObservable, reaction } from "mobx"; import { debounce } from 'lodash'; class ComponentsStore { components: DraggablePropsType[] = []; constructor() { makeAutoObservable(this); this.loadFromLocalStorage(); // 初始化加载 // 监听 components 变化自动保存(防抖版) reaction( () => this.components.slice(), // 深度监听变化 debounce(() => this.saveToLocalStorage(), 500) ); } // 初始化时从本地存储加载 private loadFromLocalStorage() { if (window === undefined) { return } const data = localStorage.getItem("componentsStore"); if (data) { try { this.components = JSON.parse(data); } catch (e) { console.error("Failed to parse stored components", e); } } } // 防抖保存到本地存储 private saveToLocalStorage = debounce(() => { localStorage.setItem("componentsStore", JSON.stringify(this.components)); }, 100); // 以下方法会触发自动保存 initComponent(componentsList: DraggablePropsType[]) { this.components = componentsList || []; } changeComponent(updatedComponent: DraggablePropsType) { this.components = this.components.map(item => item.id === updatedComponent.id ? updatedComponent : item ); } deleteComponent(targetComponent: DraggablePropsType) { this.components = this.components.filter( item => item.id !== targetComponent.id ); } addComponent(widgetsId: string, data:Record) { this.components.push({ id: String(this.components.length), x: 0, y: 0, width: 0, height: 0, widgetsId, data, }) } } export default new ComponentsStore();