From ddeb696602e664b19aa59bc63ae088e19895e7b9 Mon Sep 17 00:00:00 2001 From: feige996 <1020102647@qq.com> Date: Fri, 27 Jun 2025 23:29:19 +0800 Subject: [PATCH] =?UTF-8?q?refactor(hooks):=20=E4=BC=98=E5=8C=96useRequest?= =?UTF-8?q?=E7=B1=BB=E5=9E=8B=E5=AE=9A=E4=B9=89=E5=92=8C=E8=BF=94=E5=9B=9E?= =?UTF-8?q?=E5=80=BC=E5=A4=84=E7=90=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 将UnwrapRef替换为更明确的Ref类型 - 添加IUseRequestReturn接口明确返回值类型 - 调整data类型为可选的T | undefined - 简化响应数据处理逻辑 --- src/hooks/useRequest.ts | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/src/hooks/useRequest.ts b/src/hooks/useRequest.ts index 80ff33d..017a710 100644 --- a/src/hooks/useRequest.ts +++ b/src/hooks/useRequest.ts @@ -1,4 +1,4 @@ -import type { UnwrapRef } from 'vue' +import type { Ref } from 'vue' interface IUseRequestOptions { /** 是否立即执行 */ @@ -7,6 +7,13 @@ interface IUseRequestOptions { initialData?: T } +interface IUseRequestReturn { + loading: Ref + error: Ref + data: Ref + run: () => Promise +} + /** * useRequest是一个定制化的请求钩子,用于处理异步请求和响应。 * @param func 一个执行异步请求的函数,返回一个包含响应数据的Promise。 @@ -18,15 +25,15 @@ interface IUseRequestOptions { export default function useRequest( func: () => Promise>, options: IUseRequestOptions = { immediate: false }, -) { +): IUseRequestReturn { const loading = ref(false) const error = ref(false) - const data = ref(options.initialData) + const data = ref(options.initialData) as Ref const run = async () => { loading.value = true return func() .then((res) => { - data.value = res.data as UnwrapRef + data.value = res.data error.value = false return data.value })