参考:vue单页面应用刷新网页后vuex的state数据丢失的解决方案
1、产生原因
ans : Vuex 的状态存储是响应式的,当 Vue 组件从 store 中读取状态的时候,若 store 中的状态发生变化,那么相应的组件也会相应地得到高效更新。但是有一个问题就是:vuex的存储的数据相当于我们定义的全局变量,刷新之后,里边的数据就会恢复到初始化状态 。store里的数据是保存在运行内存中的,当页面刷新时,页面会重新加载vue实例,store里的数据就会被重新赋值。
2、 解决思路
ans:将state里的数据保存一份到本地存储:localStorage
sessionStorage
cookie
中
3、解决过程
-
选择合适的客户端存储
localStorage
:永久存储在本地,除非主动去删除sessionStorage
:是存储到当前页面关闭为止cookie
:根据你设置的有效时间来存储,但缺点是不能储存大数据且不易读取
选择sessionStorage
,理由是:- vue为单页面应用,操作都是在一个页面跳转路由
sessionStorage
可以保证打开页面时,sessionStorage
的数据为空。如果是localStorage
,则会读取上一次打开页面的数据
-
如何用
sessionStorage
来存储state中的数据- 不可行的方案:由于
state
里的数据是响应式,所以sessionStorage
存储也要跟随变化。又由于vuex规定所有state
里数据必须通过mutation
方法来修改,所以第一种方案就是mutation
修改state
的同时修改sessionStorage
对应存储的属性。但如果要这样做的话不如直接用sessionStorage
做状态管理 - 可行方案:在点击页面刷新时先将
state
中的数据保存到sessionStorage
,然后才真正刷新页面。通过window.addEventListener("beforeunload",()=>{ })
监听页面刷新,beforeunload
这个事件是在页面刷新时先触发的。在app.vue
中监听事件beforeunload
,可以保证每次刷新页面都可以触发,。
- 不可行的方案:由于
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))
})
}
}