2023-02-10 vuex持久化

一、插件:vuex-persistedstate

二、使用:

import Vue from 'vue';
import Vuex from 'vuex';
import createPersistedState from 'vuex-persistedstate';
Vue.use(Vuex);
const store = new Vuex.Store({
  state:{
    a:1,
    b:2,
  },
  plugins: [
    createPersistedState({//local持久化
      key:"project",
      storage:window.localStorage,
      reducer(val){
        return {
          token:val.a,
        }
      },
    }),
    createPersistedState({//session持久化
      key:"project",
      storage:window.sessionStorage,
      reducer(val){
        return {
          search:val.b,
        }
      },
    })
  ]
});
export default store;

三、優(yōu)點(diǎn)
1、解決頁(yè)面刷新,vuex中存放的數(shù)據(jù)丟失問(wèn)題
2、在項(xiàng)目開(kāi)發(fā)過(guò)程中更易維護(hù)緩存中存放的數(shù)據(jù),緩存中所有存放的數(shù)據(jù)在代碼中可清晰看見(jiàn)。
3、統(tǒng)一緩存中寫(xiě)入與讀取的入口。

四、注意事項(xiàng)
1、vuex-persistedstate是通過(guò)調(diào)取mutations中的方法更新state數(shù)據(jù)時(shí)同步存到緩存中的,所以,state的初始值是不會(huì)存放到緩存中且通過(guò)this.$store.state.a = 1方式修改state的值也是不會(huì)觸發(fā)同步緩存的。
2、緩存的中的數(shù)據(jù)不會(huì)反向同步到state中,解決方案:

const projectLocal= window.localStorage.getItem("project") ? JSON.parse(window.localStorage.getItem("project")) : {};
const projectSession= window.sessionStorage.getItem("project") ? JSON.parse(window.sessionStorage.getItem("project")) : {};
const state = {
    a:projectLocal.a? projectLocal.a: 1,
    b:projectSession.b? projectSession.b: 2,
};
export default state;

3、因?yàn)閘ocalStorage中存放的數(shù)據(jù)是在瀏覽器中,所以如果同時(shí)打開(kāi)多個(gè)頁(yè)面時(shí),修改localStorage中的值是不會(huì)同步到每個(gè)頁(yè)面的,如果需求需要同步可以配合緩存監(jiān)聽(tīng)使用,或根據(jù)具體需求采取更優(yōu)的解決方案。

 window.addEventListener("storage",()=>{});//緩存修改時(shí)當(dāng)前展示的頁(yè)面不會(huì)觸發(fā),其他頁(yè)面會(huì)觸發(fā)。
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容