解決vue頁(yè)面刷新,數(shù)據(jù)丟失的問(wèn)題
在做vue項(xiàng)目的過(guò)程中有時(shí)候會(huì)遇到一個(gè)問(wèn)題,就是進(jìn)行F5頁(yè)面刷新的時(shí)候,頁(yè)面的數(shù)據(jù)會(huì)丟失,出現(xiàn)這個(gè)問(wèn)題的原因是因?yàn)楫?dāng)用vuex做全局狀態(tài)管理的時(shí)候,store中的數(shù)據(jù)是保存在運(yùn)行內(nèi)存中的,頁(yè)面刷新時(shí)會(huì)重新加載vue實(shí)例,store中的數(shù)據(jù)就會(huì)被重新賦值,因此數(shù)據(jù)就丟失了,解決方式如下:
解決方法一:
最先想到的應(yīng)該就是利用localStorage/sessionStorage將數(shù)據(jù)儲(chǔ)存在外部,做一個(gè)持久化儲(chǔ)存,下面是利用localStorage存儲(chǔ)的具體方案:
方案一:由于state中的數(shù)據(jù)是響應(yīng)式的,而數(shù)據(jù)又是通過(guò)mutation來(lái)進(jìn)行修改,故在通過(guò)mutation修改state中數(shù)據(jù)的同時(shí)調(diào)用localStorage.setItem()方法來(lái)進(jìn)行數(shù)據(jù)的存儲(chǔ)。
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
export default new Vuex.Store({
state: {
orderList: [],
menuList: []
},
mutations: {
orderList(s, d) {
s.orderList= d;
window.localStorage.setItem("list",JSON.stringify(s.orderList))
},
menuList(s, d) {
s.menuList = d;
window.localStorage.setItem("list",JSON.stringify(s.menuList))
},
}
})
在頁(yè)面加載的時(shí)候再通過(guò)localStorage.getItem()將數(shù)據(jù)取出放回到vuex,可在app.vue的created()周期函數(shù)中寫(xiě)如下代碼:
if (window.localStorage.getItem("list") ) {
this.$store.replaceState(Object.assign({},
this.$store.state,JSON.parse(window.localStorage.getItem("list"))))
}
方案二:方案一能夠順利解決問(wèn)題,但不斷觸發(fā)localStorage.setItem()方法對(duì)性能不是特別友好,而且一直將數(shù)據(jù)同步到localStorage中似乎就沒(méi)必要再用vuex做狀態(tài)管理,直接用localStorage即可,于是對(duì)以上解決方法進(jìn)行了改進(jìn),通過(guò)監(jiān)聽(tīng)beforeunload事件來(lái)進(jìn)行數(shù)據(jù)的localStorage存儲(chǔ),beforeunload事件在頁(yè)面刷新時(shí)進(jìn)行觸發(fā),具體做法是在App.vue的created()周期函數(shù)中下如下代碼:
if (window.localStorage.getItem("list") ) {
this.$store.replaceState(Object.assign({}, this.$store.state,JSON.parse(window.localStorage.getItem("list"))))
}
window.addEventListener("beforeunload",()=>{
window.localStorage.setItem("list",JSON.stringify(this.$store.state))
})
解決方法二(推薦):
這個(gè)方法是基于對(duì)computed計(jì)算屬性的理解,在vue的官方文檔中有這么一段話:

由此得知計(jì)算屬性的結(jié)果會(huì)被緩存,也就是說(shuō)在有緩存的情況下,computed會(huì)優(yōu)先使用緩存,于是也可以在state數(shù)據(jù)相對(duì)應(yīng)的頁(yè)面這樣寫(xiě):
computed:{
orderList() {
return this.$store.state.orderList
}
}
以上就是解決vue頁(yè)面刷新,數(shù)據(jù)丟失的問(wèn)題的詳細(xì)內(nèi)容,更多關(guān)于vue頁(yè)面刷新,數(shù)據(jù)丟失的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
vue.js將unix時(shí)間戳轉(zhuǎn)換為自定義時(shí)間格式
這篇文章主要介紹了vue.js將unix時(shí)間戳轉(zhuǎn)換為自定義時(shí)間格式的方法,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-01-01
Vue組合式API如何正確解構(gòu)props不會(huì)丟失響應(yīng)性
響應(yīng)式?API?賦予了組合式?API?一大坨可能性的同時(shí),代碼精簡(jiǎn),雖然但是,我們應(yīng)該意識(shí)到響應(yīng)性的某些陷阱,比如丟失響應(yīng)性,在本文中,我們將學(xué)習(xí)如何正確解構(gòu)?Vue?組件的?props,使得?props?不會(huì)丟失響應(yīng)性2024-01-01
Electron主進(jìn)程(Main?Process)與渲染進(jìn)程(Renderer?Process)通信詳解
這篇文章主要介紹了Electron主進(jìn)程(Main?Process)與渲染進(jìn)程(Renderer?Process)通信,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-03-03

