From f69515952ba09bcd2005611469475640b7b43dcb Mon Sep 17 00:00:00 2001 From: Jinliang Date: Sat, 8 Jun 2024 15:56:47 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E5=A2=9E=E5=BC=BA=20useRequest=20?= =?UTF-8?q?=E9=92=A9=E5=AD=90=EF=BC=8C=E5=A2=9E=E5=8A=A0=E8=BF=94=E5=9B=9E?= =?UTF-8?q?=E5=80=BC=E5=92=8C=E9=94=99=E8=AF=AF=E5=A4=84=E7=90=86=20-=20?= =?UTF-8?q?=E5=9C=A8=20`run`=20=E5=87=BD=E6=95=B0=E4=B8=AD=E5=A2=9E?= =?UTF-8?q?=E5=8A=A0=20`return=20func()`=EF=BC=8C=E7=A1=AE=E4=BF=9D=20`run?= =?UTF-8?q?`=20=E5=87=BD=E6=95=B0=E8=BF=94=E5=9B=9E=20Promise=EF=BC=8C?= =?UTF-8?q?=E4=BB=A5=E4=BE=BF=E8=B0=83=E7=94=A8=E8=80=85=E5=8F=AF=E4=BB=A5?= =?UTF-8?q?=E7=AD=89=E5=BE=85=E5=85=B6=E5=AE=8C=E6=88=90=E3=80=82=20-=20?= =?UTF-8?q?=E5=9C=A8=20`run`=20=E5=87=BD=E6=95=B0=E4=B8=AD=E6=B7=BB?= =?UTF-8?q?=E5=8A=A0=20`return=20data.value`=EF=BC=8C=E4=BB=A5=E4=BE=BF?= =?UTF-8?q?=E8=AF=B7=E6=B1=82=E6=88=90=E5=8A=9F=E6=97=B6=E8=BF=94=E5=9B=9E?= =?UTF-8?q?=E5=93=8D=E5=BA=94=E6=95=B0=E6=8D=AE=E3=80=82=20-=20=E5=9C=A8?= =?UTF-8?q?=20`run`=20=E5=87=BD=E6=95=B0=E4=B8=AD=E6=B7=BB=E5=8A=A0=20`thr?= =?UTF-8?q?ow=20err`=EF=BC=8C=E4=BB=A5=E4=BE=BF=E8=AF=B7=E6=B1=82=E5=A4=B1?= =?UTF-8?q?=E8=B4=A5=E6=97=B6=E6=8A=9B=E5=87=BA=E9=94=99=E8=AF=AF=E3=80=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 这些更改允许调用者直接访问请求结果,并使用 `try...catch` 来处理错误,不必监听data和error处理数据或者错误,从而提高 `useRequest` 钩子的可用性和健壮性。 使用示例: const { run } = useRequest(fetchData, { immediate: false }) try { const result = await run() console.log('成功:', result) } catch (err) { console.error('失败:', err) } --- src/hooks/useRequest.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/hooks/useRequest.ts b/src/hooks/useRequest.ts index 0559276..9d1c5a7 100644 --- a/src/hooks/useRequest.ts +++ b/src/hooks/useRequest.ts @@ -24,13 +24,15 @@ export default function useRequest( const data = ref(options.initialData) const run = async () => { loading.value = true - func() + return func() .then((res) => { data.value = res.data as UnwrapRef error.value = false + return data.value }) .catch((err) => { error.value = err + throw err }) .finally(() => { loading.value = false