123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657 |
- import { onMounted, ref, type Ref } from "vue";
- import type { ILoaderCommon, LoaderLoadType } from "./LoaderCommon";
- 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,
- ) : 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';
- 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 = '' + e;
- loadStatus.value = 'error';
- console.log(e);
-
- }
- }
- onMounted(() => {
- if (loadWhenMounted) {
- setTimeout(() => {
- loadData();
- }, (0.5 + Math.random()) * 500);
- }
- })
- return {
- content,
- loadStatus,
- loadError,
- loadData,
- getLastParams: () => lastParams,
- }
- }
|