wip
This commit is contained in:
@@ -1,29 +1,69 @@
|
||||
import { DraggablePropsType } from "@/components/Draggable/Draggable";
|
||||
import { makeAutoObservable } from "mobx";
|
||||
import { makeAutoObservable, reaction } from "mobx";
|
||||
import { debounce } from 'lodash';
|
||||
|
||||
class ComponentsStore {
|
||||
components:DraggablePropsType[] = [];
|
||||
components: DraggablePropsType[] = [];
|
||||
|
||||
constructor() {
|
||||
makeAutoObservable(this);
|
||||
this.loadFromLocalStorage(); // 初始化加载
|
||||
|
||||
// 监听 components 变化自动保存(防抖版)
|
||||
reaction(
|
||||
() => this.components.slice(), // 深度监听变化
|
||||
debounce(() => this.saveToLocalStorage(), 500)
|
||||
);
|
||||
}
|
||||
|
||||
initComponent(componentsList:DraggablePropsType[]) {
|
||||
// 初始化时从本地存储加载
|
||||
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(componentsList:DraggablePropsType) {
|
||||
this.components = this.components.map(item => {
|
||||
if (item.id !== componentsList.id) {
|
||||
return item;
|
||||
}
|
||||
return componentsList;
|
||||
})
|
||||
changeComponent(updatedComponent: DraggablePropsType) {
|
||||
this.components = this.components.map(item =>
|
||||
item.id === updatedComponent.id ? updatedComponent : item
|
||||
);
|
||||
}
|
||||
|
||||
delectComponent(componentsList:DraggablePropsType) {
|
||||
this.components = this.components.filter(item => item.id !== componentsList.id);
|
||||
deleteComponent(targetComponent: DraggablePropsType) {
|
||||
this.components = this.components.filter(
|
||||
item => item.id !== targetComponent.id
|
||||
);
|
||||
}
|
||||
|
||||
addComponent(componentsId: string, data:Record<string, unknown>) {
|
||||
this.components.push({
|
||||
id: String(this.components.length),
|
||||
x: 0,
|
||||
y: 0,
|
||||
width: 0,
|
||||
height: 0,
|
||||
componentsId,
|
||||
data,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
export default new ComponentsStore();
|
||||
export default new ComponentsStore();
|
||||
|
||||
Reference in New Issue
Block a user