| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495 |
- import { onPullDownRefresh, onReachBottom } from "@dcloudio/uni-app";
- import { 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);
- })
- return {
- list,
- total,
- page,
- status,
- error,
- load,
- reload: () => load(true),
- }
- }
|