useAppContext.ts
697 Bytes
import { inject, InjectionKey, provide, reactive, readonly as defineReadonly } from 'vue'
export interface CreateContextOptions {
  readonly?: boolean
  createProvider?: boolean
  native?: boolean
}
export function createContext<T>(context: any, key: InjectionKey<T> = Symbol(), options: CreateContextOptions = {}) {
  const { readonly, createProvider, native } = options
  const state = reactive(context)
  const provideData = readonly ? defineReadonly(state) : state
  !createProvider && provide(key, native ? context : provideData)
  return {
    state
  }
}
export function useContext<T>(key: InjectionKey<T> = Symbol(), defaultValue?: any) {
  return inject(key, defaultValue || {})
}