vuex4.x持久化插件,将vuex缓存到sessionStorage中
定义插件
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)
}
欢迎大佬们指教~