我測(cè)試使用的是腳手架2
vuex是一個(gè)很好用的狀態(tài)管理模式,但是當(dāng)我們先將數(shù)據(jù)保存到store中,然后重新刷新頁(yè)面會(huì)發(fā)現(xiàn)store中的數(shù)據(jù)被重置了,這是因?yàn)閟tore中的數(shù)據(jù)存儲(chǔ)在內(nèi)存之中。
解決辦法:既然內(nèi)存中數(shù)據(jù)刷新會(huì)丟失,那么就可以在刷新的時(shí)候?qū)?shù)據(jù)保存到本地緩存,下次加載store中的數(shù)據(jù)時(shí)先去緩存中獲取,沒有緩存再加載默認(rèn)初始值
1.方法1:
1.1刷新時(shí)緩存???
我們想要在刷新的時(shí)候進(jìn)行緩存數(shù)據(jù)操作,我們就需要使用windows的unload事件,我們來看看這個(gè)unload事件:

解釋截圖
我們刷新頁(yè)面的時(shí)候就可以觸發(fā)這個(gè)unload事件,GOOD?。?!
1.2何時(shí)添加監(jiān)聽事件???
我們知道整個(gè)vue的生命周期首先在main.js中掛載一堆東西,然后掛載一個(gè)app組件,我們很想趁早添加這個(gè)unload的事件監(jiān)聽,但是為了保證main.js的簡(jiǎn)潔性,我們選擇將這個(gè)監(jiān)聽放在app組件的created鉤子函數(shù)中
//示例代碼..
methods:{
//將store中的數(shù)據(jù)存放到sessionStorage
saveState() {
sessionStorage.setItem("state", JSON.stringify(this.$store.state));
}
},
created() {
//向window添加unload事件
window.addEventListener("unload", this.saveState);
}
1.3sessionStorage???

文檔截圖
1.4修改state數(shù)據(jù)加載
之前我們一直是每次加載store直接去獲取默認(rèn)值,現(xiàn)在我們需要先去看看緩存中是否有數(shù)據(jù)
//示例代碼:
const state = sessionStorage.getItem('state') ? JSON.parse(sessionStorage.getItem('state')):{默認(rèn)值}
1.5現(xiàn)在我們就可以在刷新頁(yè)面的時(shí)候一直能保持store中的數(shù)據(jù)了
2.方法2:
2.1下載插件:
npm install --save vuex-persistedstate
2.使用示例代碼:
import Vue from 'vue'
import Vuex from 'vuex'
import persistedState from 'vuex-persistedstate'
import state from './state.js'
import mutations from './mutations.js'
import getters from './getters.js'
Vue.use(Vuex)
const store = new Vuex.Store({
plugins: [
persistedState({ storage: window.sessionStorage })
],
state:state,
mutations:mutations,
getters:getters
})
export default store