/** * shared/composables/useOffsetPagination.ts * 用途:管理端偏移分页的页码计算与导航辅助。 * 依赖:vue computed/ref/unref。 * 逻辑:PaginationBar、报表页等复用 pageButtons 与翻页方法。 */ import { computed, unref, type ComputedRef, type Ref } from 'vue'; export interface UseOffsetPaginationOptions { page: Ref; pageSize: Ref; total: Ref | ComputedRef; /** 服务端已计算总页数时传入,优先于 total/pageSize 推算 */ pages?: Ref | ComputedRef; } const DEFAULT_PAGE_SIZE_OPTIONS = [10, 20, 50, 100] as const; /** * 根据当前页与总页数生成带省略号的页码按钮序列(-1 表示 ...)。 * 核心逻辑:页数较多时开头仅展示 1–3 页,末尾仅展示最后 3 页,中间展示当前页邻域。 * @param current - 当前页(1-based) * @param totalPages - 总页数 */ export function buildOffsetPageButtons(current: number, totalPages: number): number[] { const total = Math.max(1, totalPages); const page = Math.min(Math.max(1, current), total); if (total <= 5) return Array.from({ length: total }, (_, i) => i + 1); if (page <= 3) return [1, 2, 3, -1, total]; if (page >= total - 2) return [1, -1, total - 2, total - 1, total]; return [1, -1, page - 1, page, page + 1, -1, total]; } /** * 提供偏移分页的 totalPages、range 与翻页辅助。 * @param options.page - 当前页码 ref * @param options.pageSize - 每页条数 ref * @param options.total - 总条数 ref/computed * @param options.pages - 可选,服务端返回的总页数 */ export function useOffsetPagination(options: UseOffsetPaginationOptions) { const totalPages = computed(() => { const explicit = options.pages ? Math.max(1, Number(unref(options.pages)) || 1) : 0; if (explicit > 0) return explicit; const size = Math.max(1, Number(unref(options.pageSize)) || 20); const total = Math.max(0, Number(unref(options.total)) || 0); return Math.max(1, Math.ceil(total / size)); }); const safePage = computed(() => Math.min(Math.max(1, Number(unref(options.page)) || 1), totalPages.value), ); const rangeStart = computed(() => { const total = Math.max(0, Number(unref(options.total)) || 0); if (total === 0) return 0; const size = Math.max(1, Number(unref(options.pageSize)) || 20); return (safePage.value - 1) * size + 1; }); const rangeEnd = computed(() => { const total = Math.max(0, Number(unref(options.total)) || 0); if (total === 0) return 0; const size = Math.max(1, Number(unref(options.pageSize)) || 20); return Math.min(rangeStart.value + size - 1, total); }); const pageButtons = computed(() => buildOffsetPageButtons(safePage.value, totalPages.value)); /** * 跳转到指定页,自动 clamp 到合法范围。 * @param page - 目标页码 */ const goToPage = (page: number): void => { options.page.value = Math.min(Math.max(1, page), totalPages.value); }; /** 上一页 */ const prevPage = (): void => { goToPage(safePage.value - 1); }; /** 下一页 */ const nextPage = (): void => { goToPage(safePage.value + 1); }; return { totalPages, safePage, rangeStart, rangeEnd, pageButtons, goToPage, prevPage, nextPage, pageSizeOptions: DEFAULT_PAGE_SIZE_OPTIONS, }; }