解决vuex保存的数据刷新页面时清空

参考文章: 

vuex中store保存的数据,刷新页面会清空

主要解决代码:

1、更改store文件下index文件state的定义

const store = new Vuex.Store({
    state:sessionStorage.getItem('state') ? JSON.parse(sessionStorage.getItem('state')): {
        //id
        skillId:'',
        //技能状态
        checkStatus:''
    }
})

2、在App.vue中添加

     mounted() {
            window.addEventListener('unload', this.saveState)
        },
        methods: {
            saveState() {
                sessionStorage.setItem('state', JSON.stringify(this.$store.state))
            }
        }

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

主要解决代码:

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))
    })
  }
}

猜你喜欢

转载自www.cnblogs.com/rachelch/p/11798477.html