Skip to content

Javascript快速实现Undo和Redo

核心实现逻辑

js
/**
 * 保存当前快照数据,正常情况下进行数据变动时都需要调用此函数记录当前状态,才可后续进行Undo和Redo
 * @param state 当前快照
 */
const saveCurrentStatus = (currentStatus) => {
  snapshotData.value[++snapshotIndex.value] = deepClone(currentStatus)
  if(snapshotIndex.value < snapshotData.value.length -1){
    snapshotData.value = snapshotData.value.slice(0,snapshotIndex.value + 1)
  }
}

/**
 * Undo实现函数
 */
const handleUndo = () => {
  if(snapshotIndex.value >= 0){
    snapshotIndex.value--
    const componentData = deepClone(snapshotData.value[snapshotIndex.value] || [])

    // 自己的业务逻辑不用管
    if(curComponent.value){
      //如果当前组件不在componentData中则置空
      const needClean = !componentData.find((component:any) => curComponent.value.id === component.id)
      if(needClean){
        curComponent.value = {}
      }
    }

    // 此处的componentData即是undo后的值,直接赋值即可,忽略widgets
    widgets.value = deepClone(componentData)
  } 
}

/**
 * Redo实现函数
 */
const handleRedo = () => {
  if(snapshotIndex.value < snapshotData.value.length - 1){
    snapshotIndex.value++
    const data = deepClone(snapshotData.value[snapshotIndex.value])

    // 此处的data即是redo后最新的值,直接赋值即可,忽略widgets
    widgets.value = data
  }
}

上次更新于: