| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109 |
- 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,
- }
- }
- export async function useSSrSimpleDataLoader<T, P = any>(
- name: string,
- loader: (params?: P) => Promise<T>,
- params : P|undefined = undefined,
- emptyIfArrayEmpty = true,
- ) : Promise<ISimpleDataLoader<T, P>>
- {
- const route = useRoute();
- let lastParams: P | undefined = params;
- const loadStatus = ref<LoaderLoadType>('finished');
- const loadError = ref('');
- const { data: content, error } = (await useAsyncData(route.fullPath + '/' + name, () => loader(lastParams)))
- async function loadData(params?: P, refresh: boolean = false) {
- if (!import.meta.client)
- return;
- if (params)
- lastParams = params;
- loadStatus.value = 'loading';
- try {
- const res = await loader(params ?? lastParams) as T;
- content.value = res as any;
- 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);
- }
- }
- watch(error, (e) => {
- if (e) {
- loadError.value = '' + e;
- loadStatus.value = 'error';
- }
- }, { immediate: true });
-
- return {
- content: content as Ref<T|null>,
- loadStatus,
- loadError,
- loadData,
- getLastParams: () => lastParams,
- }
- }
|