SimplePageListLoader.ts 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. import { onPullDownRefresh, onReachBottom } from "@dcloudio/uni-app";
  2. import { ref, type Ref } from "vue";
  3. import type { ILoaderCommon, LoaderLoadType } from "./LoaderCommon";
  4. export interface ISimplePageListLoader<T, P> extends ILoaderCommon<P> {
  5. list: Ref<T[]>;
  6. page: Ref<number>;
  7. total: Ref<number>;
  8. }
  9. export function useSimplePageListLoader<T, P = any>(
  10. pageSize: number,
  11. loader: (page: number, pageSize: number, params?: P) => Promise<{ list: T[], total: number }>,
  12. showGlobalLoading = false,
  13. ) : ISimplePageListLoader<T, P>
  14. {
  15. const loadStatus = ref<LoaderLoadType>('loading');
  16. const loadError = ref('');
  17. const page = ref(0);
  18. const total = ref(0);
  19. const list = ref<T[]>([]) as Ref<T[]>;
  20. let lastParams: P | undefined;
  21. let loading = false;
  22. async function loadData(params?: P, refresh: boolean = false) {
  23. if (loading)
  24. return;
  25. if (params)
  26. lastParams = params;
  27. if (refresh) {
  28. page.value = 0;
  29. list.value = [];
  30. }
  31. page.value++;
  32. loadStatus.value = 'loading';
  33. loading = true;
  34. if (showGlobalLoading)
  35. uni.showLoading({ title: '加载中...' });
  36. try {
  37. const res = (await loader(page.value, pageSize, lastParams));
  38. list.value = list.value.concat(res.list as T[]);
  39. total.value = res.total;
  40. loadStatus.value = res.list.length > 0 ? 'finished' : (total.value > 0 ? 'nomore' : 'empty');
  41. loadError.value = '';
  42. loading = false;
  43. } catch(e) {
  44. loadError.value = '' + e;
  45. loadStatus.value = 'error';
  46. loading = false;
  47. } finally {
  48. if (showGlobalLoading)
  49. uni.hideLoading();
  50. }
  51. }
  52. onPullDownRefresh(() => {
  53. loadData(lastParams, true).then(() => {
  54. uni.stopPullDownRefresh();
  55. }).catch(() => {
  56. uni.stopPullDownRefresh();
  57. });
  58. });
  59. onReachBottom(() => {
  60. if (loadStatus.value == 'nomore')
  61. return;
  62. loadData(lastParams, false);
  63. });
  64. return {
  65. list,
  66. total,
  67. page,
  68. loadStatus,
  69. loadError,
  70. loadData,
  71. }
  72. }