index.mjs 1.2 KB

12345678910111213141516171819202122232425262728293031323334
  1. import { getCurrentInstance, inject, unref } from 'vue';
  2. import { isClient, computedEager } from '@vueuse/core';
  3. import { useGetDerivedNamespace } from '../use-namespace/index.mjs';
  4. import { debugWarn } from '../../utils/error.mjs';
  5. const defaultIdInjection = {
  6. prefix: Math.floor(Math.random() * 1e4),
  7. current: 0
  8. };
  9. const ID_INJECTION_KEY = Symbol("elIdInjection");
  10. const useIdInjection = () => {
  11. return getCurrentInstance() ? inject(ID_INJECTION_KEY, defaultIdInjection) : defaultIdInjection;
  12. };
  13. const useId = (deterministicId) => {
  14. const idInjection = useIdInjection();
  15. if (!isClient && idInjection === defaultIdInjection) {
  16. debugWarn(
  17. "IdInjection",
  18. `Looks like you are using server rendering, you must provide a id provider to ensure the hydration process to be succeed
  19. usage: app.provide(ID_INJECTION_KEY, {
  20. prefix: number,
  21. current: number,
  22. })`
  23. );
  24. }
  25. const namespace = useGetDerivedNamespace();
  26. const idRef = computedEager(
  27. () => unref(deterministicId) || `${namespace.value}-id-${idInjection.prefix}-${idInjection.current++}`
  28. );
  29. return idRef;
  30. };
  31. export { ID_INJECTION_KEY, useId, useIdInjection };
  32. //# sourceMappingURL=index.mjs.map