useContext.ts 927 B

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. import {
  2. InjectionKey,
  3. provide,
  4. inject,
  5. reactive,
  6. readonly as defineReadonly,
  7. UnwrapRef,
  8. } from 'vue';
  9. export interface CreateContextOptions {
  10. readonly?: boolean;
  11. createProvider?: boolean;
  12. native?: boolean;
  13. }
  14. type ShallowUnwrap<T> = {
  15. [P in keyof T]: UnwrapRef<T[P]>;
  16. };
  17. export function createContext<T>(
  18. context: any,
  19. key: InjectionKey<T> = Symbol(),
  20. options: CreateContextOptions = {},
  21. ) {
  22. const { readonly = true, createProvider = false, native = false } = options;
  23. const state = reactive(context);
  24. const provideData = readonly ? defineReadonly(state) : state;
  25. !createProvider && provide(key, native ? context : provideData);
  26. return {
  27. state,
  28. };
  29. }
  30. export function useContext<T>(key: InjectionKey<T>, native?: boolean): T;
  31. export function useContext<T>(
  32. key: InjectionKey<T> = Symbol(),
  33. defaultValue?: any,
  34. ): ShallowUnwrap<T> {
  35. return inject(key, defaultValue || {});
  36. }