本文介绍了在Vue.js vuex上回到像Undo Redo这样的国家的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何使用Vuex进行撤消/重做?我正在开发一个非常复杂的应用程序,Vue dev工具帮助我在状态之间切换很多,所以我想在我的应用程序上使用该功能。我怎样才能实现这个目标?
How do I make undo / redo using Vuex? I am working on a pretty complex app and Vue dev tools helped me a lot to switch between state, so I want that feature on my app. How can I achieve this?
推荐答案
我已经实现了如下的undo-redo:
I've implemented undo-redo as follows:
1)为vuex创建一个插件
1) create a plugin for 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中保存州的历史记录
3) save a history of the states in 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();
如果您的州的规模不大于克隆州,这是一个很好的方法。
If your state is not huge in size than cloning that states is a good approach.
这篇关于在Vue.js vuex上回到像Undo Redo这样的国家的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!