|
| 1 | +import type { |
| 2 | + UseOffsetPaginationOptions, |
| 3 | + UseOffsetPaginationReturn, |
| 4 | +} from '@vueuse/core' |
| 5 | +import type { SetRequired } from 'type-fest' |
| 6 | +import type { ComputedRef } from 'vue' |
| 7 | +import { useOffsetPagination } from '@vueuse/core' |
| 8 | +import { computed, toValue, watch } from 'vue' |
| 9 | + |
| 10 | +export interface UsePaginationOptions |
| 11 | + extends SetRequired<UseOffsetPaginationOptions, 'total'> { |
| 12 | + /** |
| 13 | + * 页码或每页数量变化时的回调 |
| 14 | + */ |
| 15 | + onChange?: (data: { page: number, pageSize: number }) => void |
| 16 | +} |
| 17 | + |
| 18 | +export interface UsePaginationReturn extends UseOffsetPaginationReturn { |
| 19 | + /** |
| 20 | + * `options.total` |
| 21 | + */ |
| 22 | + total: ComputedRef<number> |
| 23 | + /** |
| 24 | + * 跳转到指定页码 |
| 25 | + */ |
| 26 | + jumpTo: (page: number) => void |
| 27 | +} |
| 28 | + |
| 29 | +/** |
| 30 | + * 同 `useOffsetPagination`,但返回值里包含 `total` |
| 31 | + */ |
| 32 | +export function usePagination( |
| 33 | + options: UsePaginationOptions, |
| 34 | +): UsePaginationReturn { |
| 35 | + const returned = useOffsetPagination(options) as UsePaginationReturn |
| 36 | + returned.total = computed(() => toValue(options.total)) |
| 37 | + returned.jumpTo = (page) => { |
| 38 | + returned.currentPage.value = page |
| 39 | + } |
| 40 | + |
| 41 | + watch([returned.currentPage, returned.currentPageSize], () => { |
| 42 | + options.onChange?.({ |
| 43 | + page: returned.currentPage.value, |
| 44 | + pageSize: returned.currentPageSize.value, |
| 45 | + }) |
| 46 | + }) |
| 47 | + |
| 48 | + return returned |
| 49 | +} |
0 commit comments