46
loading...
This website collects cookies to deliver better user experience
npm install --save vuex-persist
VuexPersistence
from vuex-persist
. Set storage
to window.localStorage
and register vuexLocal.plugin
as a Vuex plugin. Refresh the page and then the state will be saved to LocalStorage.const vuexLocal = new VuexPersistence({
storage: window.localStorage,
});
Vue.use(Vuex);
const store = new Vuex.Store<State>({
state: { ... },
mutations: { ... },
actions: { ... },
plugins: [vuexLocal.plugin],
});
export default store;
npm install --save localforage
localForage
implements a simple, localStorage-like API for IndexedDB, which is compatible with vuex-persist. Import localForage
from the package and set storage
to localForage
. Since localForage
storage is asynchronous, set the asyncStorage
option to true
.import Vue from 'vue';
import Vuex from 'vuex';
import VuexPersistence from 'vuex-persist';
import localForage from 'localforage';
const vuexLocal = new VuexPersistence({
storage: localForage,
asyncStorage: true,
});
Vue.use(Vuex);
const store = new Vuex.Store<State>({
state: { ... },
mutations: { ... },
actions: { ... },
plugins: [vuexLocal.plugin],
});
export default store;
localForage
is promise-based storage, the state will not be immediately restored into Vuex. It will go into the event loop and will finish when the JS thread is empty, which could invoke a delay of few seconds. vuex-persist
injected a restored
property to the store
object, which contains a Promise that will be resolved after the state is restored. The beforeEach()
hook in vue-router
could cause the app to wait for vuex-persist
to restore the state before taking any further actions.import Vue from 'vue';
import Router from 'vue-router';
import { store } from '@/store'; // the location of Vuex store
Vue.use(Router);
const router = new Router({
// define the routes
});
router.beforeEach(async (to, from, next) => {
await store.restored;
next();
});
export default router;