vue單頁應用在頁面刷新時保留狀態數據的方法


在Vue單頁應用中,如果在某一個具體路由的具體頁面下點擊刷新,那么刷新后,頁面的狀態信息可能就會丟失掉。這時候應該怎么處理呢?如果你也有這個疑惑,這篇文章或許能夠幫助到你

一、問題

現在產品上有個需求:單頁應用走到某個具體的頁面,然后點擊刷新后,刷新的頁面要與刷新前的頁面要保持一致。

這時候就需要我們保存刷新之前頁面的狀態。

二、一種解決方案

在這個Vue單頁應用中,王二是用Vuex作為狀態管理的,一開始王二的思路是將Vuex里的數據同步更新到localStorage里。

即:一改變vuex里的數據,便觸發localStorage.setItem 方法,參考如下代碼:

import Vue from "vue"
import Vuex from "vuex"
  
Vue.use(Vuex)
  
function storeLocalStore (state) {
  window.localStorage.setItem("userMsg",JSON.stringify(state));
}
  
export default new Vuex.Store({
  state: {
    username: "王二",
    schedulename: "標題",
    scheduleid: 0,
  },
  mutations: {
    storeUsername (state,name) {
      state.username = name
      storeLocalStore (state)
    },
    storeSchedulename (state,name) {
      state.schedulename = name
      storeLocalStore (state)
    },
    storeScheduleid (state,id) {
      state.scheduleid = Number(id)
      storeLocalStore (state)
    },
  }
})

然后在頁面加載時再從localStorage里將數據取回來放到vuex里,於是王二在 App.vue 的 created 鈎子函數里寫下了如下代碼:

localStorage.getItem("userMsg") && this.$store.replaceState(JSON.parse(localStorage.getItem("userMsg")));
  
//考慮到第一次加載項目時localStorage里沒有userMsg的信息,所以在前面要先做判斷

這樣就能比較圓滿的解決問題了。

三、另一種解決方案

以上的解決方法由於要頻繁地觸發 localStorage.setItem 方法,所以對性能很不友好。而且如果一直同步vuex里的數據到localStorage里,我們直接用localStorage做狀態管理好了,似乎也沒有必要再用vuex。

這時候王二想,如果有什么方法能夠監聽到頁面的刷新事件,然后在那個監聽方法里將Vuex里的數據儲存到localStorage里,那該多好。

很幸運,還真有這樣的監聽事件,我們可以用 beforeunload 來達到以上目的,於是王二在 App.vue 的 created 鈎子函數里寫下了如下代碼:

 //在頁面加載時讀取localStorage里的狀態信息
  localStorage.getItem("userMsg") && this.$store.replaceState(JSON.parse(localStorage.getItem("userMsg")));
  
  //在頁面刷新時將vuex里的信息保存到localStorage里
  window.addEventListener("beforeunload",()=>{
    localStorage.setItem("userMsg",JSON.stringify(this.$store.state))
  })

這樣的話,似乎就比較完美了。

2018年03月27日補充:

王二在使用上述方法時,遇到了一個問題,就是:在開發階段,如果在Vuex里添加新的字段,則新的字段不能被保存到localStorage里,於是上述代碼修改如下:

  //在頁面加載時讀取localStorage里的狀態信息
  localStorage.getItem("userMsg") && this.$store.replaceState(Object.assign(this.$store.state,JSON.parse(localStorage.getItem("userMsg"))));
  
  //在頁面刷新時將vuex里的信息保存到localStorage里
  window.addEventListener("beforeunload",()=>{
    localStorage.setItem("userMsg",JSON.stringify(this.$store.state))
  })

原文鏈接:https://blog.csdn.net/aliven1/article/details/80743470


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM