SimplePageContentLoader.ts 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. import { onMounted, 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. options?: {
  9. immediate?: boolean;
  10. }
  11. ) : ISimplePageContentLoader<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. loadStatus.value = 'finished';
  25. loadError.value = '';
  26. } catch(e) {
  27. loadError.value = '' + e;
  28. loadStatus.value = 'error';
  29. }
  30. }
  31. onMounted(() => {
  32. if (options?.immediate)
  33. loadData();
  34. });
  35. return {
  36. content,
  37. loadStatus,
  38. loadError,
  39. loadData,
  40. }
  41. }