import { ref, watch, type Ref } from 'vue' export type TableFetcher = (page: number, pageSize: number) => Promise<{ items: T[]; total: number }> type Options = { pageSize?: number /** 为 false 时不自动监听页码变化(如同一页面存在多个列表) */ autoWatch?: boolean } /** * 列表页通用状态:分页、加载、失败标记与重试、删除后停留有效页码。 * 错误提示由请求层统一弹出,这里只负责记录失败态供页面展示重试按钮。 */ export function useTableQuery(fetcher: TableFetcher, options: Options = {}) { const items: Ref = ref([]) const total = ref(0) const page = ref(1) const pageSize = ref(options.pageSize ?? 20) const loading = ref(false) const loadError = ref(false) const load = async () => { loading.value = true loadError.value = false try { const data = await fetcher(page.value, pageSize.value) items.value = data.items total.value = data.total const maxPage = Math.max(1, Math.ceil(data.total / pageSize.value)) if (page.value > maxPage) { page.value = maxPage return } } catch { loadError.value = true } finally { loading.value = false } } const search = () => { if (page.value === 1) load() else page.value = 1 } /** 删除一条后刷新,并保证页码停留在有效范围内 */ const refreshAfterRemove = () => { const remaining = Math.max(0, total.value - 1) const nextPage = Math.max(1, Math.min(page.value, Math.ceil(remaining / pageSize.value) || 1)) if (nextPage !== page.value) page.value = nextPage else load() } if (options.autoWatch !== false) watch(page, () => load()) return { items, total, page, pageSize, loading, loadError, load, search, refreshAfterRemove } }