vben
2021-01-05 31ff0559fe3b635fc2091aac0e2f5e340629134c
提交 | 用户 | age
74e62c 1 import {
V 2   InjectionKey,
3   provide,
4   inject,
5   reactive,
6   readonly as defineReadonly,
7   defineComponent,
8   UnwrapRef,
9 } from 'vue';
0692b4 10
74e62c 11 export interface CreateContextOptions {
V 12   readonly?: boolean;
13   createProvider?: boolean;
31ff05 14   native?: boolean;
74e62c 15 }
41d790 16
74e62c 17 type ShallowUnwrap<T> = {
V 18   [P in keyof T]: UnwrapRef<T[P]>;
0692b4 19 };
V 20
74e62c 21 export function createContext<T>(
V 22   context: any,
23   key: InjectionKey<T> = Symbol(),
24   options: CreateContextOptions = {}
25 ) {
31ff05 26   const { readonly = true, createProvider = false, native = false } = options;
74e62c 27
V 28   const state = reactive(context);
29   const provideData = readonly ? defineReadonly(state) : state;
31ff05 30   !createProvider && provide(key, native ? context : provideData);
74e62c 31
V 32   const Provider = createProvider
33     ? defineComponent({
34         name: 'Provider',
35         inheritAttrs: false,
36         setup(_, { slots }) {
37           provide(key, provideData);
38           return () => slots.default?.();
39         },
40       })
41     : null;
42
43   return { Provider, state };
44 }
45
31ff05 46 export function useContext<T>(key: InjectionKey<T>, native?: boolean): T;
V 47 export function useContext<T>(key: InjectionKey<T>, defaultValue?: any, native?: boolean): T;
74e62c 48
31ff05 49 export function useContext<T>(
V 50   key: InjectionKey<T> = Symbol(),
51   defaultValue?: any
52 ): ShallowUnwrap<T> {
53   return inject(key, defaultValue || {});
54 }