如何使用 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/