ny
22 小时以前 282fbc6488f4e8ceb5fda759f963ee88fbf7b999
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import type { InjectionKey, UnwrapRef } from 'vue';
 
import {
  readonly as defineReadonly,
  inject,
  provide,
  reactive,
  // defineComponent,
} from 'vue';
 
export interface CreateContextOptions {
  createProvider?: boolean;
  native?: boolean;
  readonly?: boolean;
}
 
type ShallowUnwrap<T> = {
  [P in keyof T]: UnwrapRef<T[P]>;
};
 
export function createContext<T>(
  context: any,
  key: InjectionKey<T> = Symbol('key'),
  options: CreateContextOptions = {},
) {
  const { createProvider = false, native = false, readonly = true } = 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>, native?: boolean): T;
 
export function useContext<T>(
  key: InjectionKey<T> = Symbol('key'),
  defaultValue?: any,
): ShallowUnwrap<T> {
  return inject(key, defaultValue || {});
}