vuex-persist數據持久化存儲插件


Vuex 解決了多視圖之間的數據共享問題。但是運用過程中又帶來了一個新的問題是,Vuex 的狀態存儲並不能持久化。也就是說當你存儲在 Vuex 中的 store 里的數據,只要一刷新頁面,數據就丟失了。

引入vuex-persist 插件,它就是為 Vuex 持久化存儲而生的一個插件。不需要你手動存取 storage ,而是直接將狀態保存至 cookie 或者 localStorage 中。具體用法如下

pexels-photo-1211847.jpeg

安裝:

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

 

原文


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM