在Vue.js vuex上回到像Undo Redo这样的国家

时间:2017-03-18 18:35:45

标签: javascript vue.js vuex

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

2 个答案:

答案 0 :(得分:7)

我已经实现了undo-redo,如下所示:

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();

如果你的州的规模不大于克隆国家是一个好方法。

答案 1 :(得分:6)

请参阅:https://vuex.vuejs.org/en/api.html

您可以轻松使用subscribe(handler: Function)注册一个函数,该函数可以将给定Store中所需的所有状态保存在数组中。

然后,您可以通过将它们作为参数提供给replaceState(state: Object)来使用该数组中的任何已保存状态。