您現在的位置是:首頁 > 網路遊戲首頁網路遊戲

解決VUE頁面重新整理,資料丟失「建議收藏」

簡介在vue專案中有時候會遇到一個問題,就是進行頁面重新整理的時候,導致頁面的資料丟失,出現這個問題的原因是因為當用vuex做全域性狀態管理的時候,store中的資料是儲存在執行記憶體中的,頁面重新整理時會重新載入vue例項,store中的資料

重新整理頁面vuex資料還在嗎

解決VUE頁面重新整理,資料丟失「建議收藏」

在vue專案中有時候會遇到一個問題,就是進行頁面重新整理的時候,導致頁面的資料丟失,出現這個問題的原因是因為當用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()週期函式中下如下程式碼:

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計算屬性的理解,計算屬性是基於他們的響應式依賴進行快取的

由此得出計算屬性的結果會被快取,也就是說在有快取的情況下,computed會優先使用快取,也可以在state資料相對應的頁面這樣寫:

computed:{

orderList() {

return this。$store。state。orderList

}

}

Top