解決vue頁面刷新,數據丟失的問題
在做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 }}
以上就是解決vue頁面刷新,數據丟失的問題的詳細內容,更多關于vue頁面刷新,數據丟失的資料請關注好吧啦網其它相關文章!