- 資訊首頁(yè) > 開(kāi)發(fā)技術(shù) > web開(kāi)發(fā) > JavaScript >
- vuex數據持久化的兩種實(shí)現方案
在基于vue開(kāi)發(fā)SPA項目時(shí),為了解決頁(yè)面刷新后數據丟失的問(wèn)題,我們一般都是將數據存儲在localstorage或sessionstorage中;當數據需要全局處理統一管理時(shí),我們也會(huì )借助于vue官方提供的vuex來(lái)進(jìn)行數據的統一管理。vuex相比localstorage或sessionstorage來(lái)說(shuō),存儲數據更安全些。與此同時(shí),vuex也存在一些弊端,當頁(yè)面刷新后,vuex中state存儲的數據同時(shí)也會(huì )被更新,vuex中存儲的數據不能持久化,需要監聽(tīng)處理來(lái)維持vuex存儲的數據狀態(tài)持久化。
為解決頁(yè)面刷新后vuex中存儲的數據狀態(tài)不能持久化的問(wèn)題,我采取的方案是借助第三方插件工具來(lái)實(shí)現vuex數據的持久化存儲,來(lái)解決頁(yè)面刷新后數據更新的問(wèn)題。
安裝插件
yarn add vuex-persistedstate // 或 npm install --save vuex-persistedstate
使用方法
import Vuex from "vuex"; // 引入插件 import createPersistedState from "vuex-persistedstate"; Vue.use(Vuex); const state = {}; const mutations = {}; const actions = {}; const store = new Vuex.Store({ state, mutations, actions, /* vuex數據持久化配置 */ plugins: [ createPersistedState({ // 存儲方式:localStorage、sessionStorage、cookies storage: window.sessionStorage, // 存儲的 key 的key值 key: "store", render(state) { // 要存儲的數據:本項目采用es6擴展運算符的方式存儲了state中所有的數據 return { ...state }; } }) ] }); export default store;
vuex中module數據的持久化存儲
/* module.js */ export const dataStore = { state: { data: [] } } /* store.js */ import { dataStore } from './module' const dataState = createPersistedState({ paths: ['data'] }); export new Vuex.Store({ modules: { dataStore }, plugins: [dataState] });
注意事項:
安裝插件
yarn add vuex-persist // 或 npm install --save vuex-persist
使用方法
import Vuex from "vuex"; // 引入插件 import VuexPersistence from "vuex-persist"; Vue.use(Vuex); // 初始化 const state = { userName:'admin' }; const mutations = {}; const actions = {}; // 創(chuàng )建實(shí)例 const vuexPersisted = new VuexPersistence({ storage: window.sessionStorage, render:state=>({ userName:state.userName // 或 ...state }) }); const store = new Vuex.Store({ state, actions, mutations, // 數據持久化設置 plugins:[vuexPersisted.plugins] }); export default store;
屬性方法
上述兩種方案都可以實(shí)現vuex數據持久化存儲。方案一是我在實(shí)際開(kāi)發(fā)過(guò)程中用到的,方案二是在Github上看到的,綜合來(lái)說(shuō),兩者都可以時(shí)間最終的需求,而且都有對應的案例Demo可以參考。相比來(lái)說(shuō)方案一在GitHub上的start數要高于方案二。
請結合實(shí)際情況選擇符合自己的方案!
到此這篇關(guān)于vuex數據持久化的兩種實(shí)現方案的文章就介紹到這了,更多相關(guān)vuex數據持久化內容請搜索腳本之家以前的文章或繼續瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng )、來(lái)自本網(wǎng)站內容采集于網(wǎng)絡(luò )互聯(lián)網(wǎng)轉載等其它媒體和分享為主,內容觀(guān)點(diǎn)不代表本網(wǎng)站立場(chǎng),如侵犯了原作者的版權,請告知一經(jīng)查實(shí),將立刻刪除涉嫌侵權內容,聯(lián)系我們QQ:712375056,同時(shí)歡迎投稿傳遞力量。
Copyright ? 2009-2022 56dr.com. All Rights Reserved. 特網(wǎng)科技 特網(wǎng)云 版權所有 特網(wǎng)科技 粵ICP備16109289號
域名注冊服務(wù)機構:阿里云計算有限公司(萬(wàn)網(wǎng)) 域名服務(wù)機構:煙臺帝思普網(wǎng)絡(luò )科技有限公司(DNSPod) CDN服務(wù):阿里云計算有限公司 百度云 中國互聯(lián)網(wǎng)舉報中心 增值電信業(yè)務(wù)經(jīng)營(yíng)許可證B2
建議您使用Chrome、Firefox、Edge、IE10及以上版本和360等主流瀏覽器瀏覽本網(wǎng)站