一、插件: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ā)。