store里的数据是保存在运行内存中的,当页面刷新时,页面会重新加载vue实例,store 里面的数据就会被重新赋值初始化;
解决方法
(1)localStorage永久存储,除非用户自己删除;
(2)sessionStorage在同源的窗口中存储数据,关闭窗口会删除;
(3)cookie在设置的cookie过期时间内有效,大小为4K左右,不能储存大数据且不易读取
推荐方法
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))
})
}