Skip to content

Instantly share code, notes, and snippets.

@Bomberus
Last active June 14, 2018 06:05
Show Gist options
  • Save Bomberus/104a7a435b277965f0f8b35251d93b2b to your computer and use it in GitHub Desktop.
Save Bomberus/104a7a435b277965f0f8b35251d93b2b to your computer and use it in GitHub Desktop.
Vuex-persist localstorage sync
import Vuex, {Payload, Store} from 'vuex'
import VuexPersistence from 'vuex-persist'
const vuexLocal = new VuexPersistence<State, Payload> ({
strictMode: true,
storage: window.localStorage,
filter: mutation => mutation.type !== 'RELOAD_MUTATION'
})
const store = new Vuex.Store<State>({
strict: true,
mutations: {
RESTORE_MUTATION: vuexLocal.RESTORE_MUTATION,
RELOAD_MUTATION: (state, payload) => {
state = payload
//vuexLocal.RESTORE_MUTATION(state, payload) //Use vuex-persist mutation (working but throws error)
}
},
modules: {
...
},
plugins: [vuexLocal.plugin]
})
export default store
//Sync internal state
window.addEventListener('storage', event => {
if (event.newValue === null) return;
if (event.key !== 'vuex') return;
if (event.oldValue === event.newValue) return;
const newState = JSON.parse(event.newValue)
//console.log(newState)
store.commit('RELOAD_MUTATION', newState)
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment