import { ref, watch, type Ref } from 'vue' export type ServerPageFetcher = (pageNum: number, pageSize: number) => Promise<{ list: T[] total: number }> /** * 服务端分页:翻页/改 pageSize 时重新请求(不自动 immediate,由页面 resetAndLoad 触发)。 */ export function useServerPagination( fetcher: ServerPageFetcher, options?: { pageSize?: number }, ) { const page = ref(1) const pageSize = ref(options?.pageSize ?? 10) const total = ref(0) const list = ref([]) as Ref const loading = ref(false) let skipWatch = false async function load() { loading.value = true try { const res = await fetcher(page.value, pageSize.value) list.value = res.list || [] total.value = Number(res.total || 0) } finally { loading.value = false } } async function resetAndLoad() { skipWatch = true page.value = 1 skipWatch = false await load() } watch(page, () => { if (skipWatch) return void load() }) watch(pageSize, () => { skipWatch = true page.value = 1 skipWatch = false void load() }) return { page, pageSize, total, list, loading, load, resetAndLoad, } }