vuex-persistedstate
安裝
npm install vuex-persistedstate --save
使用
import createPersistedState from "vuex-persistedstate"
const store =newVuex.Store({
state: {},
mutations: {},
actions: {},
// 存儲(chǔ)到 localStorege
plugins: [createPersistedState()]
// 存儲(chǔ)到 sessionStorage
plugins: [createPersistedState({
storage:window.sessionStorage
})]
})
需要持久化的數(shù)據(jù)
import createPersistedState from "vuex-persistedstate"
const store = newVuex.Store({
state: {},
mutations: {},
actions: {},
plugins: [createPersistedState({
storage:window.sessionStorage,
reducer(val) {
return {
// 只儲(chǔ)存state中的token
assessmentData: val.token
}
}
})]
})
vuex-persist
- 它就是為 Vuex 持久化存儲(chǔ)而生的一個(gè)插件徐许。不需要你手動(dòng)存取
storage
,而是直接將狀態(tài)保存至 cookie 或者 localStorage
中
安裝
npm install --save vuex-persist
or
yarn add vuex-persist
使用
import VuexPersistence from 'vuex-persist'
const vuexLocal = new VuexPersistence({
storage: window.localStorage
})
const store = new Vuex.Store({
state: {},
mutations: {},
actions: {},
plugins: [vuexLocal.plugin]
})
- 通過(guò)以上設(shè)置,在圖3中各個(gè)頁(yè)面之間跳轉(zhuǎn)赦邻,如果刷新某個(gè)視圖,數(shù)據(jù)并不會(huì)丟失实檀,依然存在惶洲,并且不需要在每個(gè)
mutations
中手動(dòng)存取 storage
vuex-persist 的詳細(xì)屬性:
key |
string |
將狀態(tài)存儲(chǔ)在存儲(chǔ)中的鍵。默認(rèn): 'vuex' |
storage |
Storage (Web API) 可傳localStorage, sessionStorage, localforage 或者你自定義的存儲(chǔ)對(duì)象. |
接口必須要有g(shù)et和set. 默認(rèn)是: window.localStorage |
saveState |
function (key, state[, storage]) |
如果不使用存儲(chǔ)膳犹,這個(gè)自定義函數(shù)將保存狀態(tài)保存為持久性恬吕。 |
restoreState |
function (key[, storage]) => state |
如果不使用存儲(chǔ),這個(gè)自定義函數(shù)處理從存儲(chǔ)中檢索狀態(tài) |
reducer |
function (state) => object |
將狀態(tài)減少到只需要保存的值须床。默認(rèn)情況下铐料,保存整個(gè)狀態(tài)。 |
filter |
function (mutation) => boolean |
突變篩選豺旬∧瞥停看mutation.type并返回true,只有那些你想堅(jiān)持寫(xiě)被觸發(fā)族阅。所有突變的默認(rèn)返回值為true篓跛。 |
modules |
string[] |
要持久化的模塊列表。 |