SimpleDataLoader.ts 1.6 KB

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