解決vue頁面刷新,數(shù)據(jù)丟失

來源 | https://www.cnblogs.com/tp51/p/14026035.html
解決方法一:
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))},}})
在頁面加載的時(shí)候再通過localStorage.getItem()將數(shù)據(jù)取出放回到vuex,可在app.vue的created()周期函數(shù)中寫如下代碼:
if (window.localStorage.getItem("list") ) {this.$store.replaceState(Object.assign({},this.$store.state,JSON.parse(window.localStorage.getItem("list"))))}
方案二:方案一能夠順利解決問題,但不斷觸發(fā)localStorage.setItem()方法對(duì)性能不是特別友好,而且一直將數(shù)據(jù)同步到localStorage中似乎就沒必要再用vuex做狀態(tài)管理,直接用localStorage即可,于是對(duì)以上解決方法進(jìn)行了改進(jìn),通過監(jiān)聽beforeunload事件來進(jìn)行數(shù)據(jù)的localStorage存儲(chǔ),beforeunload事件在頁面刷新時(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ì)被緩存,也就是說在有緩存的情況下,computed會(huì)優(yōu)先使用緩存,于是也可以在state數(shù)據(jù)相對(duì)應(yīng)的頁面這樣寫:
computed:{orderList() {return this.$store.state.orderList}}

評(píng)論
圖片
表情
