usePagination.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. import _extends from "@babel/runtime/helpers/esm/extends";
  2. import useState from '../../_util/hooks/useState';
  3. import { computed } from 'vue';
  4. import extendsObject from '../../_util/extendsObject';
  5. export const DEFAULT_PAGE_SIZE = 10;
  6. export function getPaginationParam(mergedPagination, pagination) {
  7. const param = {
  8. current: mergedPagination.current,
  9. pageSize: mergedPagination.pageSize
  10. };
  11. const paginationObj = pagination && typeof pagination === 'object' ? pagination : {};
  12. Object.keys(paginationObj).forEach(pageProp => {
  13. const value = mergedPagination[pageProp];
  14. if (typeof value !== 'function') {
  15. param[pageProp] = value;
  16. }
  17. });
  18. return param;
  19. }
  20. export default function usePagination(totalRef, paginationRef, onChange) {
  21. const pagination = computed(() => paginationRef.value && typeof paginationRef.value === 'object' ? paginationRef.value : {});
  22. const paginationTotal = computed(() => pagination.value.total || 0);
  23. const [innerPagination, setInnerPagination] = useState(() => ({
  24. current: 'defaultCurrent' in pagination.value ? pagination.value.defaultCurrent : 1,
  25. pageSize: 'defaultPageSize' in pagination.value ? pagination.value.defaultPageSize : DEFAULT_PAGE_SIZE
  26. }));
  27. // ============ Basic Pagination Config ============
  28. const mergedPagination = computed(() => {
  29. const mP = extendsObject(innerPagination.value, pagination.value, {
  30. total: paginationTotal.value > 0 ? paginationTotal.value : totalRef.value
  31. });
  32. // Reset `current` if data length or pageSize changed
  33. const maxPage = Math.ceil((paginationTotal.value || totalRef.value) / mP.pageSize);
  34. if (mP.current > maxPage) {
  35. // Prevent a maximum page count of 0
  36. mP.current = maxPage || 1;
  37. }
  38. return mP;
  39. });
  40. const refreshPagination = (current, pageSize) => {
  41. if (paginationRef.value === false) return;
  42. setInnerPagination({
  43. current: current !== null && current !== void 0 ? current : 1,
  44. pageSize: pageSize || mergedPagination.value.pageSize
  45. });
  46. };
  47. const onInternalChange = (current, pageSize) => {
  48. var _a, _b;
  49. if (paginationRef.value) {
  50. (_b = (_a = pagination.value).onChange) === null || _b === void 0 ? void 0 : _b.call(_a, current, pageSize);
  51. }
  52. refreshPagination(current, pageSize);
  53. onChange(current, pageSize || mergedPagination.value.pageSize);
  54. };
  55. return [computed(() => {
  56. return paginationRef.value === false ? {} : _extends(_extends({}, mergedPagination.value), {
  57. onChange: onInternalChange
  58. });
  59. }), refreshPagination];
  60. }