| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100 |
- import { onPullDownRefresh, onReachBottom } from "@dcloudio/uni-app";
- import { computed, onMounted, ref, type Ref } from "vue";
- import type { ILoaderCommon, LoaderLoadType } from "./LoaderCommon";
- export interface ISimplePageListLoader<T, P> extends ILoaderCommon<P> {
- list: Ref<T[]>;
- page: Ref<number>;
- total: Ref<number>;
- }
- /**
- * 说明:
- * * 简单页面分页列表加载器组合式代码。
- * @param pageSize 每页数量
- * @param loader 数据加载函数
- * @param showGlobalLoading 是否显示全局加载提示
- */
- export function useSimplePageListLoader<T, P = any>(
- pageSize: number,
- loader: (page: number, pageSize: number, params?: P) => Promise<{ list: T[], total: number }>,
- loadWhenMounted = true,
- showGlobalLoading = false,
- ) : ISimplePageListLoader<T, P>
- {
-
- const status = ref<LoaderLoadType>('loading');
- const error = ref('');
- const page = ref(0);
- const total = ref(0);
- const list = ref<T[]>([]) as Ref<T[]>;
- 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);
- })
- const isLoaded = computed(() => {
- return status.value === 'finished' || status.value === 'nomore';
- });
- return {
- list,
- total,
- page,
- status,
- error,
- load,
- reload: () => load(true),
- isLoaded,
- }
- }
|