useContext.ts 593 B

12345678910111213141516171819202122
  1. import { InjectionKey, provide, inject, reactive, readonly } from 'vue';
  2. export const createContext = <T>(
  3. context: any,
  4. contextInjectKey: InjectionKey<T> = Symbol(),
  5. _readonly = true
  6. ) => {
  7. const state = reactive({
  8. ...context,
  9. });
  10. const provideData = _readonly ? readonly(state) : state;
  11. provide(contextInjectKey, provideData);
  12. };
  13. export const useContext = <T>(
  14. contextInjectKey: InjectionKey<T> = Symbol(),
  15. defaultValue?: any,
  16. _readonly = true
  17. ): T => {
  18. const state = inject(contextInjectKey, defaultValue || {});
  19. return _readonly ? readonly(state) : state;
  20. };