Vben
2021-03-27 979058ad95d9669cb113033f76b5dafb932aad0f
提交 | 用户 | age
74e62c 1 import {
V 2   InjectionKey,
3   provide,
4   inject,
5   reactive,
6   readonly as defineReadonly,
a89eee 7   // defineComponent,
74e62c 8   UnwrapRef,
V 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
a89eee 32   // const Provider = createProvider
V 33   //   ? defineComponent({
34   //       name: 'Provider',
35   //       inheritAttrs: false,
36   //       setup(_, { slots }) {
37   //         provide(key, provideData);
38   //         return () => slots.default?.();
39   //       },
40   //     })
41   //   : null;
74e62c 42
a89eee 43   return {
V 44     // Provider,
45     state,
46   };
74e62c 47 }
V 48
31ff05 49 export function useContext<T>(key: InjectionKey<T>, native?: boolean): T;
V 50 export function useContext<T>(key: InjectionKey<T>, defaultValue?: any, native?: boolean): T;
74e62c 51
31ff05 52 export function useContext<T>(
V 53   key: InjectionKey<T> = Symbol(),
54   defaultValue?: any
55 ): ShallowUnwrap<T> {
56   return inject(key, defaultValue || {});
57 }