博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
解决vue页面刷新,数据丢失
阅读量:4117 次
发布时间:2019-05-25

本文共 1792 字,大约阅读时间需要 5 分钟。

来源 | https://www.cnblogs.com/tp51/p/14026035.html

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

解决方法一:

最先想到的应该就是利用localStorage/sessionStorage将数据储存在外部,做一个持久化储存,下面是利用localStorage存储的具体方案:

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

方案二:方案一能够顺利解决问题,但不断触发localStorage.setItem()方法对性能不是特别友好,而且一直将数据同步到localStorage中似乎就没必要再用vuex做状态管理,直接用localStorage即可,于是对以上解决方法进行了改进,通过监听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计算属性的理解,在vue的官方文档中有这么一段话:

由此得知计算属性的结果会被缓存,也就是说在有缓存的情况下,computed会优先使用缓存,于是也可以在state数据相对应的页面这样写:

computed:{   orderList() {       return this.$store.state.orderList   }}

本文完~

你可能感兴趣的文章
pow(x,n) 为什么错这么多次
查看>>
Jump Game 动态规划
查看>>
Binary Tree Maximum Path Sum 自底向上求解(重重重重)
查看>>
Subsets 深搜
查看>>
Subsets II
查看>>
Edit Distance 字符串距离(重重)
查看>>
Gray Code 格雷码
查看>>
对话周鸿袆:从程序员创业谈起
查看>>
web.py 0.3 新手指南 - 如何用Gmail发送邮件
查看>>
web.py 0.3 新手指南 - RESTful doctesting using app.request
查看>>
web.py 0.3 新手指南 - 使用db.query进行高级数据库查询
查看>>
web.py 0.3 新手指南 - 多数据库使用
查看>>
一步步开发 Spring MVC 应用
查看>>
python: extend (扩展) 与 append (追加) 的差别
查看>>
「译」在 python 中,如果 x 是 list,为什么 x += "ha" 可以运行,而 x = x + "ha" 却抛出异常呢?...
查看>>
浅谈JavaScript的语言特性
查看>>
LeetCode第39题思悟——组合总和(combination-sum)
查看>>
LeetCode第43题思悟——字符串相乘(multiply-strings)
查看>>
LeetCode第44题思悟——通配符匹配(wildcard-matching)
查看>>
LeetCode第45题思悟——跳跃游戏(jump-game-ii)
查看>>