add use api

This commit is contained in:
2026-07-14 23:55:32 +07:00
parent a2b8094ff7
commit 549082443b
+65
View File
@@ -0,0 +1,65 @@
import { ref, type Ref } from 'vue';
export type ApiMethod<T, P = void> = (params: P) => Promise<T>;
interface UseApiOptions<T> {
immediate?: boolean;
onSuccess?: (data: T) => void;
onError?: (error: Error) => void;
}
export function useApi<T, P = void>(
method: ApiMethod<T, P>,
params?: P,
options: UseApiOptions<T> = {}
) {
const data = ref<T | null>(null) as Ref<T | null>;
const loading = ref(false);
const error = ref<Error | null>(null);
const execute = async (execParams?: P) => {
loading.value = true;
error.value = null;
try {
const result = await method(execParams !== undefined ? execParams : (params as P));
data.value = result;
options.onSuccess?.(result);
return result;
} catch (e) {
const err = e instanceof Error ? e : new Error('Unknown error');
error.value = err;
options.onError?.(err);
throw err;
} finally {
loading.value = false;
}
};
const reset = () => {
data.value = null;
loading.value = false;
error.value = null;
};
// Автоматический запуск
if (options.immediate !== false) {
execute();
}
return {
data,
loading,
error,
execute,
reset,
};
}
// Упрощенная версия для GET-запросов
export function useApiData<T, P = void>(
method: ApiMethod<T, P>,
params?: P
) {
return useApi(method, params, { immediate: true });
}