useContext.ts 1.0 KB

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