解決vuex保存的數據刷新頁面時清空


關於頁面刷新導致vuex(store)里面的數據消失問題,解決思路:

通過監聽頁面刷新或者關閉來將 vuex 里面的數據保存到 sessionStorage 里,在頁面加載時讀取 sessionStorage 里的狀態信息,更新 vuex 的數據

【方法一】

參考文章: vuex中store保存的數據,刷新頁面會清空

主要解決代碼:

1、更改store文件下index文件state的定義

const store = new Vuex.Store({
    state:sessionStorage.getItem('state') ? JSON.parse(sessionStorage.getItem('state')): {
        //id
        skillId:'',
        //技能狀態
        checkStatus:''
    }
})

 

2、在App.vue中添加

     mounted() {
            window.addEventListener('unload', this.saveState)
        },
        methods: {
            saveState() {
                sessionStorage.setItem('state', JSON.stringify(this.$store.state))
            }
        }

 

【方法二】

 參考文章:vue單頁面應用刷新網頁后vuex的state數據丟失的解決方案

主要解決代碼:

export default {
  name: 'App',
  created () {
    //在頁面加載時讀取sessionStorage里的狀態信息
    if (sessionStorage.getItem("store") ) {
        this.$store.replaceState(Object.assign({}, this.$store.state,JSON.parse(sessionStorage.getItem("store"))))
    } 

    //在頁面刷新時將vuex里的信息保存到sessionStorage里
    window.addEventListener("beforeunload",()=>{
        sessionStorage.setItem("store",JSON.stringify(this.$store.state))
    })
  }
}

 !!!【注意】

beforeunload 事件在 ios 上不兼容,刷新頁面時無法執行

解決方案: 使用 pagehide 代替 beforeunload

即:

window.addEventListener('pagehide', () => {
     sessionStorage.setItem('store', JSON.stringify(this.$store.state))
})

 參考文章: 解決移動端無法監聽頁面刷新或關閉(beforeunload無效)問題

 


免責聲明!

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



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