Files
taimed-international-app/hooks/useRequest.ts
2025-11-04 12:37:04 +08:00

36 lines
704 B
TypeScript

// hooks/useRequest.ts
import { ref } from 'vue'
interface IUseRequestOptions<T> {
immediate?: boolean
initialData?: T
}
export function useRequest<T>(
func: () => Promise<T>,
options: IUseRequestOptions<T> = { immediate: false },
) {
const loading = ref(false)
const error = ref<any>(null)
const data = ref<T | undefined>(options.initialData)
const run = async () => {
loading.value = true
error.value = null
try {
const res = await func()
data.value = res
return res
} catch (err) {
error.value = err
throw err
} finally {
loading.value = false
}
}
options.immediate && run()
return { loading, error, data, run }
}