SimpleDataLoader.ts 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. import { onMounted, ref, type Ref } from "vue";
  2. import type { ILoaderCommon, LoaderLoadType } from "./LoaderCommon";
  3. export interface ISimpleDataLoader<T, P> extends ILoaderCommon<P> {
  4. content: Ref<T|null>;
  5. getLastParams: () => P | undefined;
  6. }
  7. export function useSimpleDataLoader<T, P = any>(
  8. loader: (params?: P) => Promise<T>,
  9. loadWhenMounted = true,
  10. emptyIfArrayEmpty = true,
  11. ) : ISimpleDataLoader<T, P>
  12. {
  13. const content = ref<T|null>(null) as Ref<T|null>;
  14. const loadStatus = ref<LoaderLoadType>('loading');
  15. const loadError = ref('');
  16. let lastParams: P | undefined;
  17. async function loadData(params?: P) {
  18. if (params)
  19. lastParams = params;
  20. loadStatus.value = 'loading';
  21. try {
  22. const res = (await loader(params ?? lastParams)) as T;
  23. content.value = res;
  24. if (Array.isArray(res) && emptyIfArrayEmpty && (res as any[]).length === 0)
  25. loadStatus.value = 'nomore';
  26. else
  27. loadStatus.value = 'finished';
  28. loadError.value = '';
  29. } catch(e) {
  30. loadError.value = '' + e;
  31. loadStatus.value = 'error';
  32. console.log(e);
  33. }
  34. }
  35. onMounted(() => {
  36. if (loadWhenMounted) {
  37. setTimeout(() => {
  38. loadData();
  39. }, (0.5 + Math.random()) * 500);
  40. }
  41. })
  42. return {
  43. content,
  44. loadStatus,
  45. loadError,
  46. loadData,
  47. getLastParams: () => lastParams,
  48. }
  49. }