You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

31 lines
938 B

import type { InjectionKey, UnwrapRef } from 'vue'
import { readonly as defineReadonly, inject, provide, reactive } from 'vue'
2 years ago
export interface CreateContextOptions {
readonly?: boolean
createProvider?: boolean
native?: boolean
}
type ShallowUnwrap<T> = {
[P in keyof T]: UnwrapRef<T[P]>
}
2 years ago
export function createContext<T>(context: any, key: InjectionKey<T> = Symbol('create-context'), options: CreateContextOptions = {}) {
2 years ago
const { readonly = true, createProvider = true, native = false } = options
2 years ago
const state = reactive(context)
const provideData = readonly ? defineReadonly(state) : state
2 years ago
createProvider && provide(key, native ? context : provideData)
2 years ago
return {
state,
2 years ago
}
}
export function useContext<T>(key: InjectionKey<T>, native?: boolean): T
2 years ago
export function useContext<T>(key: InjectionKey<T> = Symbol('use-context'), defaultValue?: any): ShallowUnwrap<T> {
2 years ago
return inject(key, defaultValue || {})
}