解决vue页面刷新,数据丢失的问题

在做vue项目的过程中有时候会遇到一个问题,就是进行F5页面刷新的时候,页面的数据会丢失。
出现这个问题的原因是:因为当用vuex做全局状态管理的时候,store中的数据是保存在运行内存中的,页面刷新时会重新加载vue实例,store中的数据就会被重新赋值,因此数据就丢失了,


解决方式如下:

方法一:利用localStorage/sessionStorage将数据储存在外部,做一个持久化储存

方案1: 由于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"))))
}

方案1的缺点:不断触发localStorage.setItem()方法对性能不是特别友好,一直将数据同步到localStorage中似乎就没必要再用vuex做状态管理,直接用localStorage即可

方案2: 通过监听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))
    })

方法二:使用computed计算属性

计算属性 是基于它们的响应式依赖进行缓存的,只在相关相关响应式依赖发生改变时,他们才会重新求值。

在有缓存的情况下,computed会优先使用缓存,于是也可以在state数据相对应的页面这样写:

computed:{
   orderList() {
       return this.$store.state.orderList
   }
}
  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值