???? Vuex
是一個專為Vue.js
應(yīng)用程序開發(fā)的狀態(tài)管理模式,采用集中式管理存儲管理應(yīng)用的所有組件的狀態(tài)捅暴。但是當(dāng)刷新頁面的時候恬砂,保存在Vuex
實(shí)例store
的數(shù)據(jù)會丟失。
????原因就是:
因?yàn)?code>store里的數(shù)據(jù)是保存在運(yùn)行內(nèi)存中蓬痒,當(dāng)頁面刷新時泻骤,頁面會重新加載Vue
實(shí)例,store
里面的數(shù)據(jù)就會被重新賦值初始化梧奢。
????解決方法:
方法一:
將state
的數(shù)據(jù)保存在localstorage
,sessionstorage
或cookie
中狱掂。
-
在頁面刷新前將數(shù)據(jù)存儲到sessionstorage中,使用beforeunload事件亲轨,該事件在頁面刷新前觸發(fā):
- 在app.vue的created方法中讀取sessionstorage中的數(shù)據(jù)存儲在store中趋惨,此時用vuex.store.replaceState方法,替換store的根狀態(tài)
- 在beforeunload方法中將store.state存儲到sessionstorage中瓶埋。
代碼如下:
export default {
name: 'App',
created () {
//在頁面加載時讀取sessionStorage里的狀態(tài)信息
if (sessionStorage.getItem("state") ) {
this.$store.replaceState(Object.assign({}, this.$store.state,JSON.parse(sessionStorage.getItem("state"))))
}
//在頁面刷新時將vuex里的信息保存到sessionStorage里
window.addEventListener("beforeunload",()=>{
sessionStorage.setItem("state",JSON.stringify(this.$store.state))
})
}
localStorage
,sessionStorage
,cookie
三者的區(qū)別:
-
localStorage
:localStorage
的生命周期是永久的希柿,關(guān)閉頁面或?yàn)g覽器之后localStorage
中的數(shù)據(jù)也不會消失。localStorage
除非主動刪除數(shù)據(jù)养筒,否則數(shù)據(jù)永遠(yuǎn)不會消失曾撤。 -
sessionStorage
:sessionStorage
的生命周期是在僅在當(dāng)前會話下有效。sessionStorage
引入了一個“瀏覽器窗口”的概念晕粪,sessionStorage
是在同源的窗口中始終存在的數(shù)據(jù)挤悉。只要這個瀏覽器窗口沒有關(guān)閉,即使刷新頁面或者進(jìn)入同源另一個頁面巫湘,數(shù)據(jù)依然存在装悲。但是sessionStorage
在關(guān)閉了瀏覽器窗口后就會被銷毀昏鹃。同時獨(dú)立的打開同一個窗口同一個頁面,sessionStorage
也是不一樣的诀诊。 -
cookie
:cookie
生命期為只在設(shè)置的cookie
過期時間之前一直有效洞渤,即使窗口或?yàn)g覽器關(guān)閉属瓣。 存放數(shù)據(jù)大小為4K
左右,有個數(shù)限制(各瀏覽器不同)护昧,一般不能超過20
個。缺點(diǎn)是不能儲存大數(shù)據(jù)且不易讀取绽榛。
方法二:
????使用vuex-persistedstate
,可以自動存儲。
- 下載:
npm install --save vuex-persistedstate
- 使用
在store.js中引入
import createPersistedState from 'vuex-persistedstate'
export default new Vuex.Store({
//配置
plugins: [createPersistedState()]
})
默認(rèn)的是存儲到localStorage里的美莫,我們也可以存到sessionStorage中厢呵,如:
import createPersistedState from 'vuex-persistedstate'
export default new Vuex.Store({
//配置
plugins: [createPersistedState({
storage: window.sessionStorage
})]
})