import { onPullDownRefresh, onReachBottom } from "@dcloudio/uni-app"; import { onMounted, ref, type Ref } from "vue"; import type { ILoaderCommon, LoaderLoadType } from "./LoaderCommon"; export interface ISimplePageListLoader extends ILoaderCommon

{ list: Ref; page: Ref; total: Ref; } /** * 说明: * * 简单页面分页列表加载器组合式代码。 * @param pageSize 每页数量 * @param loader 数据加载函数 * @param showGlobalLoading 是否显示全局加载提示 */ export function useSimplePageListLoader( pageSize: number, loader: (page: number, pageSize: number, params?: P) => Promise<{ list: T[], total: number }>, loadWhenMounted = true, showGlobalLoading = false, ) : ISimplePageListLoader { const status = ref('loading'); const error = ref(''); const page = ref(0); const total = ref(0); const list = ref([]) as Ref; let lastParams: P | undefined; let loading = false; async function load(refresh: boolean = false, params?: P) { if (loading) return; if (params) lastParams = params; if (refresh) { page.value = 0; list.value = []; } page.value++; status.value = 'loading'; loading = true; if (showGlobalLoading) uni.showLoading({ title: '加载中...' }); try { const res = (await loader(page.value, pageSize, lastParams)); list.value = list.value.concat(res.list as T[]); total.value = res.total; status.value = res.list.length > 0 ? 'finished' : (list.value.length > 0 ? 'nomore' : 'empty'); error.value = ''; loading = false; } catch(e) { console.error(e); error.value = '' + e; status.value = 'error'; loading = false; } finally { if (showGlobalLoading) uni.hideLoading(); } } onPullDownRefresh(() => { load(true, lastParams).then(() => { uni.stopPullDownRefresh(); }).catch(() => { uni.stopPullDownRefresh(); }); }); onReachBottom(() => { if (status.value == 'nomore') return; load(false, lastParams); }); onMounted(() => { if (loadWhenMounted) load(false, lastParams); }) return { list, total, page, status, error, load, reload: () => load(true), } }