vuex資料持久化存儲
業務需求:
在基于vue開發spa項目時,為了解決頁面重新整理後資料丢失的問題,我們一般都是将資料存儲在localstorage或sessionstorage中;當資料需要全局處理統一管理時,我們也會借助于vue官方提供的vuex來進行資料的統一管理。vuex相比localstorage或sessionstorage來說,存儲資料更安全些。與此同時,vuex也存在一些弊端,當頁面重新整理後,vuex中state存儲的資料同時也會被更新,vuex中存儲的資料不能持久化,需要監聽處理來維持vuex存儲的資料狀态持久化。
為解決頁面重新整理後vuex中存儲的資料狀态不能持久化的問題,我采取的方案是借助第三方插件工具來實作vuex資料的持久化存儲,來解決頁面重新整理後資料更新的問題。
安裝插件
使用方法
vuex中module資料的持久化存儲
注意事項:
storage為存儲方式,可選值為localstorage、sessionstorage和cookies;
localstorage和sessionstorage兩種存儲方式可以采用上述代碼中的寫法,若想采用cookies坐位資料存儲方式,則需要另外一種寫法;
render接收一個函數,傳回值為一個對象;傳回的對象中的鍵值對既是要持久化存儲的資料;
若想持久化存儲部分資料,請在return的對象中采用key:value鍵值對的方式進行資料存儲,render函數中的參數既為state對象。
屬性方法
<col>
屬性值
資料類型
描述
key
string
the key to store the state in the storage default: 'vuex'
storage
storage (web api)
localstorage, sessionstorage, localforage or your custom storage object.must implement getitem, setitem, clear etc.default: window.localstorage
savestate
function(key, state[, storage])
if not using storage, this custom function handles saving state to persistence
restorestate
function (key[, storage]) => state
if not using storage, this custom function handles retrieving state from storage
reducer
function (state) => object
state reducer. reduces state to only those values you want to save. by default, saves entire state
filter
function (mutation) => boolean
mutation filter. look at <code>mutation.type</code> and return true for only those ones which you want a persistence write to be triggered for. default returns true for all mutations
modules
string[]
list of modules you want to persist. (do not write your own reducer if you want to use this)
asyncstorage
boolean
denotes if the store uses promises (like localforage) or not (you must set this to true when suing something like localforage) default: false
supportcircular
denotes if the state has any circular references to itself (state.x === state) default: false
上述兩種方案都可以實作vuex資料持久化存儲。方案一是我在實際開發過程中用到的,方案二是在github上看到的,綜合來說,兩者都可以時間最終的需求,而且都有對應的案例demo可以參考。相比來說方案一在github上的start數要高于方案二。
請結合實際情況選擇符合自己的方案!