Files
shanxia2.0/web-admin/src/hooks/bx/usePagedTable.ts
T
2026-06-30 23:44:22 +08:00

49 lines
1.3 KiB
TypeScript

import { computed, ref, type ComputedRef, type Ref } from 'vue'
import { DEFAULT_LIST_PAGE_SIZE } from '@/utils/table/tableConfig'
type Source<T> = Ref<T[]> | ComputedRef<T[]> | (() => T[])
interface UsePagedTableOptions {
initialPage?: number
initialPageSize?: number
}
export function usePagedTable<T>(source: Source<T>, options: UsePagedTableOptions = {}) {
const currentPage = ref(options.initialPage ?? 1)
const pageSize = ref(options.initialPageSize ?? DEFAULT_LIST_PAGE_SIZE)
const sourceRows = computed(() => {
if (typeof source === 'function') return source()
return source.value
})
const total = computed(() => sourceRows.value.length)
const pagedRows = computed(() => {
const start = (currentPage.value - 1) * pageSize.value
const end = start + pageSize.value
return sourceRows.value.slice(start, end)
})
const rangeText = computed(() => {
const count = total.value
const start = count === 0 ? 0 : (currentPage.value - 1) * pageSize.value + 1
const end = Math.min(currentPage.value * pageSize.value, count)
return `显示 ${start}-${end} / ${count}`
})
function onSizeChange() {
currentPage.value = 1
}
return {
currentPage,
pageSize,
total,
pagedRows,
rangeText,
onSizeChange
}
}