| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465 |
- import { onMounted, ref, type Ref } from "vue";
- import type { ILoaderCommon, LoaderLoadType } from "./LoaderCommon";
- import { formatError } from "./ErrorDisplay";
- export interface ISimpleDataLoader<T, P> extends ILoaderCommon<P> {
- content: Ref<T|null>;
- getLastParams: () => P | undefined;
- }
- export function useSimpleDataLoader<T, P = any>(
- loader: (params?: P) => Promise<T>,
- loadWhenMounted = true,
- emptyIfArrayEmpty = true,
- showGlobalLoading = false,
- ) : ISimpleDataLoader<T, P>
- {
- const content = ref<T|null>(null) as Ref<T|null>;
- const loadStatus = ref<LoaderLoadType>('loading');
- const loadError = ref('');
- let lastParams: P | undefined;
- async function loadData(params?: P) {
- if (params)
- lastParams = params;
- loadStatus.value = 'loading';
- if (showGlobalLoading)
- uni.showLoading({ title: '加载中...' });
- try {
- const res = (await loader(params ?? lastParams)) as T;
- content.value = res;
- if (Array.isArray(res) && emptyIfArrayEmpty && (res as any[]).length === 0)
- loadStatus.value = 'nomore';
- else
- loadStatus.value = 'finished';
- loadError.value = '';
- } catch(e) {
- loadError.value = formatError(e);
- loadStatus.value = 'error';
- console.log(e);
-
- } finally {
- if (showGlobalLoading)
- uni.hideLoading();
- }
- }
- onMounted(() => {
- if (loadWhenMounted) {
- setTimeout(() => {
- loadData();
- }, (0.5 + Math.random()) * 500);
- }
- })
- return {
- content,
- loadStatus,
- loadError,
- loadData,
- getLastParams: () => lastParams,
- }
- }
|