引入
vuex-persist 插件,它就是为 Vuex 持久化存储而生的一个插件。不需要你手动存取 storage ,而是直接将状态保存至 cookie 或者 localStorage 中。具体用法如下:
安装:
npm install --save vuex-persist
引入:import VuexPersistence from 'vuex-persist'
创建对象:
const vuexLocal = new VuexPersistence({ storage: window.localStorage })
引入到Vuex插件:
const store = new Vuex.Store({ state: { ... }, mutations: { ... }, actions: { ... }, plugins: [vuexLocal.plugin] })
通过以上设置,在各个页面之间跳转,如果刷新某个视图,数据依然存在,并且不需要在每个 mutations 中手动存取 storage 。