refactor(hooks): 优化useRequest类型定义和返回值处理

- 将UnwrapRef替换为更明确的Ref类型
- 添加IUseRequestReturn接口明确返回值类型
- 调整data类型为可选的T | undefined
- 简化响应数据处理逻辑
This commit is contained in:
feige996
2025-06-27 23:29:19 +08:00
parent 8f0e9cb3fe
commit ddeb696602

View File

@@ -1,4 +1,4 @@
import type { UnwrapRef } from 'vue'
import type { Ref } from 'vue'
interface IUseRequestOptions<T> {
/** 是否立即执行 */
@@ -7,6 +7,13 @@ interface IUseRequestOptions<T> {
initialData?: T
}
interface IUseRequestReturn<T> {
loading: Ref<boolean>
error: Ref<boolean | Error>
data: Ref<T | undefined>
run: () => Promise<T | undefined>
}
/**
* useRequest是一个定制化的请求钩子用于处理异步请求和响应。
* @param func 一个执行异步请求的函数返回一个包含响应数据的Promise。
@@ -18,15 +25,15 @@ interface IUseRequestOptions<T> {
export default function useRequest<T>(
func: () => Promise<IResData<T>>,
options: IUseRequestOptions<T> = { immediate: false },
) {
): IUseRequestReturn<T> {
const loading = ref(false)
const error = ref(false)
const data = ref<T>(options.initialData)
const data = ref<T | undefined>(options.initialData) as Ref<T | undefined>
const run = async () => {
loading.value = true
return func()
.then((res) => {
data.value = res.data as UnwrapRef<T>
data.value = res.data
error.value = false
return data.value
})