vuex可以進(jìn)行全局的狀態(tài)管理,但刷新后刷新后數(shù)據(jù)會消失咨堤,這是我們不愿意看到的发钝。怎么解決呢顿涣,我們可以結(jié)合本地存儲做到數(shù)據(jù)狀態(tài)持久化,但是太麻煩每次都要操作酝豪,強(qiáng)烈建議使用插件利用vuex-persistedstate插件.今天推薦兩種vuex-persistedstate和vuex-persist
第一種 vuex-persistedstate
插件
安裝
npm install vuex-persistedstate --save
1.使用vuex-persistedstate默認(rèn)存儲到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({
state: {},
mutations: {},
actions: {},
plugins: [createPersistedState({
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 孵淘,而是直接將狀態(tài)保存至 cookie 或者 localStorage 中蒲障。
安裝:
npm install --save vuex-persist
or
yarn add vuex-persist
引入:
import VuexPersistence from 'vuex-persist'
先創(chuàng)建一個對象并進(jìn)行配置:
const vuexLocal = new VuexPersistence({
storage: window.localStorage
})
引入進(jìn)vuex插件:
const store = new Vuex.Store({
state: {},
mutations: {},
actions: {},
plugins: [vuexLocal.plugin]
})
通過以上設(shè)置,在圖3中各個頁面之間跳轉(zhuǎn)瘫证,如果刷新某個視圖揉阎,數(shù)據(jù)并不會丟失,依然存在背捌,并且不需要在每個 mutations 中手動存取 storage 毙籽。
vuex-persist 的詳細(xì)屬性:
屬性 類型 描述
key | string | 將狀態(tài)存儲在存儲中的鍵。默認(rèn): 'vuex' |
---|---|---|
storage | Storage (Web API) 可傳localStorage, sessionStorage, localforage 或者你自定義的存儲對象. | 接口必須要有g(shù)et和set. 默認(rèn)是: window.localStorage |
saveState | function (key, state[, storage]) | 如果不使用存儲载萌,這個自定義函數(shù)將保存狀態(tài)保存為持久性惧财。 |
restoreState | function (key[, storage]) => state | 如果不使用存儲,這個自定義函數(shù)處理從存儲中檢索狀態(tài) |
reducer | function (state) => object | 將狀態(tài)減少到只需要保存的值扭仁。默認(rèn)情況下垮衷,保存整個狀態(tài)。 |
filter | function (mutation) => boolean | 突變篩選乖坠〔笸唬看mutation.type并返回true,只有那些你想堅(jiān)持寫被觸發(fā)熊泵。所有突變的默認(rèn)返回值為true仰迁。 |
modules | string[] | 要持久化的模塊列表。 |