vuex页面刷新数据丢失

一:数据丢失的原因

  • vuex存储的数据只是在页面中,相当于全局变量,页面刷新的时候vuex里的数据会重新初始化,导致数据丢失。
  • 因为vuex里的数据是保存在运行内存中的,当页面刷新时,页面会重新加载vue实例,vuex里面的数据就会被重新赋值。

二:解决的思路

  1. 将vuex中的数据直接保存到浏览器缓存中(sessionStorage、localStorage、cookie)
  2. 页面刷新后再从浏览器中取出

三:解决方法

方法一:

  1. 直接在vuex修改数据方法中将数据存储到浏览器本地存储中
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))
       },
   }
})
  1. 在页面加载时再从本地存储中取出并赋给vuex
if (window.localStorage.getItem("list") ) {
        this.$store.replaceState(Object.assign({}, 
        this.$store.state,JSON.parse(window.localStorage.getItem("list"))))
}

在此可以进行优化

  • 通过监听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))
})

 

四:总结

  • 其实解决此问题的方法有很多,基本上都是要借助于localStorage或者sessionStroage来存放。
posted @ 2023-02-14 19:20  web格调  阅读(184)  评论(0编辑  收藏  举报