Files
backend/frontend/src/composables/useApiRequest.ts
T

26 lines
737 B
TypeScript
Raw Normal View History

import { ref, readonly, type Ref } from 'vue'
export function useApiRequest<T>(fetcher: (...args: any[]) => Promise<T>) {
const data: Ref<T | null> = ref(null)
const loading = ref(false)
const error = ref<string | null>(null)
async function execute(...args: any[]): Promise<T | null> {
loading.value = true
error.value = null
try {
const result = await fetcher(...args)
data.value = result
return result
} catch (e: any) {
const msg = e?.response?.data?.detail || e?.message || '请求失败'
error.value = msg
return null
} finally {
loading.value = false
}
}
return { data: readonly(data), loading: readonly(loading), error: readonly(error), execute }
}