vuex可以进行全局的状态管理,但刷新后刷新后数据会消失,这是我们不愿意看到的。怎么解决呢,我们可以结合本地存储做到数据状态持久化,但是太麻烦每次都要操作,强烈建议使用插件利用vuex-persistedstate插件.今天推荐两种vuex-persistedstate和vuex-persist
第一种 vuex-persistedstate
插件
安装
npm install vuex-persistedstate --save
1.使用vuex-persistedstate默认存储到localStorage
- 引入及配置:在
store
下的index.js
中
import createPersistedState from "vuex-persistedstate" const store =newVuex.Store({ state: { ... }, mutations: { ... }, actions: { ... }, plugins: [createPersistedState()] })
2.使用vuex-persistedstate存储到sessionStorage
- 引入及配置:在
store
下的index.js
中
import createPersistedState from "vuex-persistedstate" const store = newVuex.Store({ plugins: [createPersistedState({ state: { ... }, mutations: { ... }, actions: { ... }, storage:window.sessionStorage })] })
3.使用vuex-persistedstate指定需要持久化的state
- 引入及配置:在
store
下的index.js
中
import createPersistedState from "vuex-persistedstate" const store = newVuex.Store({ state: { ... }, mutations: { ... }, actions: { ... }, plugins: [createPersistedState({ storage:window.sessionStorage, reducer(val) { return { // 只储存state中的token assessmentData: val.token } } })] })
第二种 引入vuex-persist 插件,它就是为 Vuex 持久化存储而生的一个插件。不需要你手动存取 storage ,而是直接将状态保存至 cookie 或者 localStorage 中。
安装:
npm install --save vuex-persist or yarn add 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] })
通过以上设置,在图3中各个页面之间跳转,如果刷新某个视图,数据并不会丢失,依然存在,并且不需要在每个 mutations 中手动存取 storage 。
vuex-persist 的详细属性:
属性 类型 描述
key | string | 将状态存储在存储中的键。默认: 'vuex' |
---|---|---|
storage | Storage (Web API) 可传localStorage, sessionStorage, localforage 或者你自定义的存储对象. | 接口必须要有get和set. 默认是: window.localStorage |
saveState | function (key, state[, storage]) | 如果不使用存储,这个自定义函数将保存状态保存为持久性。 |
restoreState | function (key[, storage]) => state | 如果不使用存储,这个自定义函数处理从存储中检索状态 |
reducer | function (state) => object | 将状态减少到只需要保存的值。默认情况下,保存整个状态。 |
filter | function (mutation) => boolean | 突变筛选。看mutation.type并返回true,只有那些你想坚持写被触发。所有突变的默认返回值为true。 |
modules | string[] | 要持久化的模块列表。 |