在做vue專案的程序中有時候會遇到一個問題,就是進行F5頁面重繪的時候,頁面的資料會丟失,出現這個問題的原因是因為當用vuex做全域狀態管理的時候,store中的資料是保存在運行記憶體中的,頁面重繪時會重新加載vue實體,store中的資料就會被重新賦值,因此資料就丟失了,解決方式如下:
解決方法一:
最先想到的應該就是利用localStorage/sessionStorage將資料儲存在外部,做一個持久化儲存,下面是利用localStorage存盤的具體方案:
方案一:由于state中的資料是回應式的,而資料又是通過mutation來進行修改,故在通過mutation修改state中資料的同時呼叫localStorage.setItem()方法來進行資料的存盤,
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)) }, } })
在頁面加載的時候再通過localStorage.getItem()將資料取出放回到vuex,可在app.vue的created()周期函式中寫如下代碼:
if (window.localStorage.getItem("list") ) { this.$store.replaceState(Object.assign({}, this.$store.state,JSON.parse(window.localStorage.getItem("list")))) }
方案二:方案一能夠順利解決問題,但不斷觸發localStorage.setItem()方法對性能不是特別友好,而且一直將資料同步到localStorage中似乎就沒必要再用vuex做狀態管理,直接用localStorage即可,于是對以上解決方法進行了改進,通過監聽beforeunload事件來進行資料的localStorage存盤,beforeunload事件在頁面重繪時進行觸發,具體做法是在App.vue的created()周期函式中下如下代碼:
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)) })
解決方法二(推薦):
這個方法是基于對computed計算屬性的理解,在vue的官方檔案中有這么一段話:

由此得知計算屬性的結果會被快取,也就是說在有快取的情況下,computed會優先使用快取,于是也可以在state資料相對應的頁面這樣寫:
computed:{ orderList() { return this.$store.state.orderList } }
本人在專案遇到的問題:
1.頁面重繪資料丟失
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/227121.html
標籤:其他
上一篇:單例模式
下一篇:tarBar沒有出現
