处理刷新页面vuex丢失

keepState.js

export default class KeepState{
    constructor(obj){
        let config = {
            storage:'sessionStorage',
            store:null,
            key:'KEEPSTATE',
            state:[]
        }
        Object.assign(config,obj)
        if(config.store&&config.state.length){
            this.handlerState(config)
        }
    }
    handlerState(config){
        let {store,state,storage,key} = config;
        let localState = window[storage][key]?JSON.parse(window[storage][key]):{};
        //将本地的state合并到store中
        state.forEach(state=>{
            if(state.includes('.')){
                let mod = state.split('.')
                let ms = Object.assign(
                    {},
                    store.state[mod[0]],
                    {
                        [mod[1]]:localState[state]?localState[state]:store.state[mod[0]][mod[1]]
                    }
                )
                store.replaceState(
                    Object.assign(
                        {},
                        store.state,
                        {
                            [mod[0]]:ms
                        }
                    )
                )
            }else{
                store.replaceState(
                    {},
                    store.state,
                    {
                        state:localState[state]?localState[state]:store[state]
                    }
                )
            }
        })
        //合并后删除本地的state
        window[storage].removeItem(key)
        //监听页面刷新前,将store中的state存到本地
        window.addEventListener('beforeunload',()=>{
            let value = {};
            state.forEach(stateKey=>{
                if(stateKey.includes('.')){
                    let mod = stateKey.split('.')
                    value[stateKey] = store.state[mod[0]][mod[1]]
                }else{
                    value[stateKey] = store.state[stateKey]
                }
            })
            window[storage].setItem(key,JSON.stringify(value))
        })
    }
}

App.vue中使用

<template>
    <div id="app">
    </div>
</template>

import KeepState from '@/utils/keepState.js'
import store from '@/store/index'
export default{
    name:'App'
    created(){
        new KeepState({
            store,
            state:['activemenu','user.username']
        })
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值