SimplePageContentLoader.ts 959 B

12345678910111213141516171819202122232425262728293031323334353637383940
  1. import { ref, type Ref } from "vue";
  2. import type { ILoaderCommon, LoaderLoadType } from "./LoaderCommon";
  3. export interface ISimplePageContentLoader<T, P> extends ILoaderCommon<P> {
  4. content: Ref<T|null>;
  5. }
  6. export function useSimplePageContentLoader<T, P = any>(
  7. loader: (params?: P) => Promise<T>
  8. ) : ISimplePageContentLoader<T, P>
  9. {
  10. const content = ref<T|null>(null) as Ref<T|null>;
  11. const loadStatus = ref<LoaderLoadType>('loading');
  12. const loadError = ref('');
  13. let lastParams: P | undefined;
  14. async function loadData(params?: P) {
  15. if (params)
  16. lastParams = params;
  17. loadStatus.value = 'loading';
  18. try {
  19. const res = (await loader(params ?? lastParams)) as T;
  20. content.value = res;
  21. loadStatus.value = 'finished';
  22. loadError.value = '';
  23. } catch(e) {
  24. loadError.value = '' + e;
  25. loadStatus.value = 'error';
  26. }
  27. }
  28. return {
  29. content,
  30. loadStatus,
  31. loadError,
  32. loadData,
  33. }
  34. }