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[] | 要持久化的模塊列表。 |