手写vuex4.x持久化插件

vuex4.x持久化插件,将vuex缓存到sessionStorage中

vuex插件

定义插件

useInitProvide.ts

import { Store, MutationPayload } from 'vuex'
import {StateProps} from './index'
// 这个是我自己存储的vuex的类型
import ComponentService from '@componentService/index'

// Nullable 为定义的一个全局类型 type Nullable<T> = T || null
const key: string = 'senior_design_vuex'
type WatchProps = Nullable<ComponentService>

export default (store: Store<StateProps>) => {
    // 将vuex的状态存储在 sessionStorage 中
    function setItem (key: string, value: string) {
        sessionStorage.setItem(key, value)
    }

    function getItem (key: string): Nullable<string> {
        return sessionStorage.getItem(key)
    }

    const data: Nullable<string> = getItem(key)
    // 初始化如果有值,覆盖
    if (data && data !== '') {
        try {
        	// 替换 store 的根状态	
            store.replaceState(JSON.parse(data))
        } catch (e) {
            console.error(e)
        }
    }

    function updateState (state: StateProps) {
        const data: Nullable<string> = getItem(key)
        try {
            setItem(key, JSON.stringify(state))
        } catch (e) {
            console.error(e)
            // 设置失败,则恢复值
            setItem(key, data ?? '')
        }
    }

	// 订阅vuex的mutation事件,当然也可以订阅其他的事件
    // store.subscribe((mutation: MutationPayload, state: StateProps) => updateState(state))

    // 监听 vuexService 更新state中的值(因为我当前项目中使用的这个vuex是一个provide,值会随时变动,所以不通过 订阅 mutation 事件来修改缓存的值,直接调用vuex的监听)
    store.watch<WatchProps>((state: StateProps) => state.vuexService, (val: WatchProps) => updateState(store.state), {deep: true})
}
使用插件
import ComponentService from '@/components/componentService'
import { createStore, Store, useStore } from 'vuex'
import { InjectionKey } from 'vue'
import persistenceVuexPlugin from './persistenceVuex'

export interface StateProps {
    vuexService: Nullable<ComponentService>
}


// 这个key是为了获取vuex的key,利用vue的provide/inject,这个作为key
export const key: InjectionKey<Store<StateProps>> = Symbol()

export const store: Store<StateProps> = createStore<StateProps>({
    state: {
        vuexService: null
    },
    mutations: {
        initService (state: StateProps, service: ComponentService) {
            state.vuexService = service
        }
    },
    // 使用插件,直接挂载即可
    plugins: [persistenceVuexPlugin]
})

// 使用vuex,使用 useStore(key) 方法
export function useGetVuex (): Store<StateProps> {
    return useStore(key)
}

欢迎大佬们指教~

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值