How can I achieve a time travel feature using Vuex ? I want to go back for a previous state, to undo something.
Is that possible out of the box ?
Any idea on how to achieve that ?
was hoping for something like store.rollback(1)
The best approach is not to keep the record of the state snapshots, but rather, keep the record of committed mutations.
To UNDO one step:
This approach is easier on the memory (esp if you have a large store), and is more in line with how the store should be treated.
A very good breakdown here:
https://vuejsdevelopers.com/2017/11/13/vue-js-vuex-undo-redo/
A working solution here:
https://github.com/anthonygore/vuex-undo-redo
Just implement it by your own, add a prevState to your store, you can only select the parts that you want to make it undo-able.
Here is the simplest example, which only support 1 history record:
store
const state = {
count: 0,
prevCount: null
}
mutations:
const INCREMENT = state => {
state.prevCount = state.count
state.count += 1
}
const UNDO = state => {
if (state.prevCount !== null) {
state.count = state.prevCount
state.prevCount = null
}
}
If you need to have more history, just put them in an array
const state = {
count: 0,
countHistory: []
}
and then you can use state.countHistory.pop()
and state.countHistory.push(xx)
to undo/save records
Another solution is plugin (middleware), in case you want to save all the history automatically.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With