思路:
- 设置一个变量
- 设置一个定时器实时更新数据
export interface EditorProps {
// 供中间编辑器渲染的数组
components: ComponentData[];
// 当前编辑的是哪个元素,uuid
currentElement: string;
// 当然最后保存的时候还有有一些项目信息,这里并没有写出,等做到的时候再补充
page: PageData;
// 当前被复制的组件
copiedComponent?: ComponentData;
// 当前操作的历史记录
histories: HistoryProps[];
// 当前历史记录的操作位置
historyIndex: number;
// 开始更新时的缓存值
cachedOldValues: any;
// 保存最多历史条目记录数
maxHistoryNumber: number;
// 数据是否有修改
** isDirty: boolean;**
// 当前 work 的 channels
channels: ChannelProps[];
}
const isDirty = computed(() => store.state.editor.isDirty)
封装函数 setDirtyWrapper
const setDirtyWrapper = (callback: Mutation<EditorProps>) => {
return (state: EditorProps, payload: any) => {
state.isDirty = true
callback(state, payload)
}
}
使用 setDirtyWrapper
addComponent: setDirtyWrapper((state, component: ComponentData) => {
component.layerName = '图层' + (state.components.length + 1)
state.components.push(component)
pushHistory(state, {
id: uuidv4(),
componentId: component.id,
type: 'add',
data: cloneDeep(component)
})
}),
在项目使用实时更新
// 自动保存
let timer = 0
onMounted(() => {
timer = window.setInterval(() => {
if (isDirty.value) {
saveWork()
}
}, 1000 * 50)
})
onUnmounted(() => {
clearInterval(timer)
})