From 9fb68fa8073f5b02b1bbf1fc94f9bd69bf551e39 Mon Sep 17 00:00:00 2001 From: feige996 <1020102647@qq.com> Date: Thu, 18 Sep 2025 09:39:38 +0800 Subject: [PATCH] =?UTF-8?q?refactor(hooks):=20=E4=BD=BF=20useRequest=20?= =?UTF-8?q?=E7=9A=84=E5=8F=82=E6=95=B0=20P=20=E5=8F=AF=E9=80=89=E5=B9=B6?= =?UTF-8?q?=E8=AE=BE=E7=BD=AE=E9=BB=98=E8=AE=A4=E7=B1=BB=E5=9E=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 修改 IUseRequestReturn 和 useRequest 的泛型参数 P 为可选,并设置默认类型为 undefined 使 run 方法的参数变为可选,提高 hook 的灵活性 --- src/hooks/useRequest.ts | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/src/hooks/useRequest.ts b/src/hooks/useRequest.ts index 731b56c..8ac4bfe 100644 --- a/src/hooks/useRequest.ts +++ b/src/hooks/useRequest.ts @@ -1,4 +1,5 @@ -import { type Ref, ref } from 'vue' +import type { Ref } from 'vue' +import { ref } from 'vue' interface IUseRequestOptions { /** 是否立即执行 */ @@ -7,11 +8,11 @@ interface IUseRequestOptions { initialData?: T } -interface IUseRequestReturn { +interface IUseRequestReturn { loading: Ref error: Ref data: Ref - run: (args: P) => Promise + run: (args?: P) => Promise } /** @@ -22,14 +23,14 @@ interface IUseRequestReturn { * @param options.initialData 初始化数据,默认为undefined。 * @returns 返回一个对象{loading, error, data, run},包含请求的加载状态、错误信息、响应数据和手动触发请求的函数。 */ -export default function useRequest( - func: (args: P) => Promise, +export default function useRequest( + func: (args?: P) => Promise, options: IUseRequestOptions = { immediate: false }, ): IUseRequestReturn { const loading = ref(false) const error = ref(false) const data = ref(options.initialData) as Ref - const run = async (args: P) => { + const run = async (args?: P) => { loading.value = true return func(args) .then((res) => {