vue单页面应用刷新网页后vuex的state数据丢失的解决方案

app.vue入口组件中添加如下代码,这样就可以保证每次刷新页面都可以触发

 1 export default {
 2   name: 'App',
 3   created () {
 4     //在页面加载时读取sessionStorage里的状态信息
 5     if (sessionStorage.getItem("store") ) {
       //this.$store.replaceState()替换 store 的根状态
6 this.$store.replaceState(Object.assign({}, this.$store.state,JSON.parse(sessionStorage.getItem("store")))) 7 } 8 9 //在页面刷新时将vuex里的信息保存到sessionStorage里 10 window.addEventListener("beforeunload",()=>{ 11 sessionStorage.setItem("store",JSON.stringify(this.$store.state)) 12 }) 13 } 14 }

原文地址:https://www.cnblogs.com/chenfan19941111/p/9970946.html