pager.ts 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. import { ref } from "vue";
  2. import { assign, parse } from "../utils";
  3. import type { Response } from "../service";
  4. type Pagination = {
  5. page: number;
  6. size: number;
  7. total: number;
  8. };
  9. type PagerResponse = {
  10. list: UTSJSONObject[];
  11. pagination: Pagination;
  12. };
  13. type PagerCallback = (params: UTSJSONObject) => Promise<UTSJSONObject>;
  14. export class Pager {
  15. public page = 1;
  16. public size = 20;
  17. public total = 0;
  18. public list = ref<UTSJSONObject[]>([]);
  19. public loading = ref(false);
  20. public refreshing = ref(false);
  21. public finished = ref(false);
  22. public params = {} as UTSJSONObject;
  23. public cb: PagerCallback | null = null;
  24. constructor(cb: PagerCallback) {
  25. this.cb = cb;
  26. }
  27. done() {
  28. this.loading.value = false;
  29. }
  30. clear() {
  31. this.list.value = [];
  32. this.finished.value = false;
  33. this.refreshing.value = false;
  34. this.loading.value = false;
  35. }
  36. public refresh = async (params: UTSJSONObject): Promise<UTSJSONObject> => {
  37. return new Promise((resolve, reject) => {
  38. assign(this.params, params);
  39. const data = {
  40. page: this.page,
  41. size: this.size,
  42. ...this.params
  43. };
  44. this.loading.value = true;
  45. this.cb!(data)
  46. .then((res) => {
  47. const { list, pagination } = parse<PagerResponse>(res)!;
  48. this.page = pagination.page;
  49. this.size = pagination.size;
  50. this.total = pagination.total;
  51. this.finished.value = this.list.value.length >= this.total;
  52. if (data.page == 1) {
  53. this.list.value = list;
  54. } else {
  55. this.list.value.push(...list);
  56. }
  57. resolve(res);
  58. })
  59. .catch((err) => {
  60. reject(err);
  61. })
  62. .finally(() => {
  63. this.loading.value = false;
  64. });
  65. });
  66. };
  67. public loadMore = () => {
  68. if (this.loading.value || this.finished.value) {
  69. return;
  70. }
  71. this.page += 1;
  72. this.refresh({});
  73. };
  74. }
  75. export function usePager(cb: PagerCallback) {
  76. return new Pager(cb);
  77. }