javascript - 回到像 Vue.js vuex 上的 Undo Redo 这样的状态

标签 javascript vue.js vuex

如何使用 Vuex 进行撤消/重做?我正在开发一个非常复杂的应用程序,Vue 开发工具帮助我在状态之间切换了很多,所以我希望我的应用程序具有该功能。我怎样才能做到这一点?

最佳答案

我已经按如下方式实现了撤消重做:

1) 为vuex创建一个插件

const undoRedoPlugin = (store) => {
  // initialize and save the starting stage
  undoRedoHistory.init(store);
  let firstState = cloneDeep(store.state);
  undoRedoHistory.addState(firstState);

  store.subscribe((mutation, state) => {
    // is called AFTER every mutation
    undoRedoHistory.addState(cloneDeep(state));
  });
}

2) 使用那个插件

new Vuex.Store({
... 
  plugins: [undoRedoPlugin]
});

3) 在undoRedoHistory中保存一个状态的历史

class UndoRedoHistory {
  store;
  history = [];
  currentIndex = -1;

  init(store) {
    this.store = store;
  }

  addState(state) {
    // may be we have to remove redo steps
    if (this.currentIndex + 1 < this.history.length) {
      this.history.splice(this.currentIndex + 1);
    }
    this.history.push(state);
    this.currentIndex++;
  }

  undo() {
    const prevState = this.history[this.currentIndex - 1];
    // take a copy of the history state
    // because it would be changed during store mutations
    // what would corrupt the undo-redo-history
    // (same on redo)
    this.store.replaceState(cloneDeep(prevState));
    this.currentIndex--;
  }

  redo() {
    const nextState = this.history[this.currentIndex + 1];
    this.store.replaceState(cloneDeep(nextState));
    this.currentIndex++;
  }
}

const undoRedoHistory = new UndoRedoHistory();

4)使用它

undoRedoHistory.undo();
...
undoRedoHistory.redo();

如果您的州规模不大,那么克隆该州是一个不错的方法。

关于javascript - 回到像 Vue.js vuex 上的 Undo Redo 这样的状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42878329/

相关文章:

javascript - Vuex、vuejs - 未按预期对选择元素选项进行绑定(bind)

javascript - 如何通过循环使用vuex中的img src

javascript - 将数据传递给 nuxt fetch,存储调度不起作用

php - 拥有一个动态页面或根据下拉选项重定向的多个页面更好吗?

javascript - 黑莓上下文菜单关闭事件

javascript - asp.net json 显示奇怪的结果

javascript - 在 vue.js 应用程序中使用外部 js 库

javascript - 如何在 feathersjs 项目中使用 sequelizejs 创建外键

javascript - 为什么 Vue 使用它是 “in-place patch” ,尽管我在 v-for 循环中绑定(bind)了一个键?

reactjs - v-for 在 react 中的等价物是什么?