diff --git a/src/hooks/useRequest.ts b/src/hooks/useRequest.ts index 0559276..9a0c8e5 100644 --- a/src/hooks/useRequest.ts +++ b/src/hooks/useRequest.ts @@ -1,7 +1,7 @@ import { UnwrapRef } from 'vue' type IUseRequestOptions = { - /** 是否立即执行,如果是则在onLoad执行 */ + /** 是否立即执行 */ immediate?: boolean /** 初始化数据 */ initialData?: T @@ -11,34 +11,34 @@ type IUseRequestOptions = { * useRequest是一个定制化的请求钩子,用于处理异步请求和响应。 * @param func 一个执行异步请求的函数,返回一个包含响应数据的Promise。 * @param options 包含请求选项的对象 {immediate, initialData}。 - * @param options.immediate 是否立即执行请求,默认为true。 + * @param options.immediate 是否立即执行请求,默认为false。 * @param options.initialData 初始化数据,默认为undefined。 * @returns 返回一个对象{loading, error, data, run},包含请求的加载状态、错误信息、响应数据和手动触发请求的函数。 */ export default function useRequest( func: () => Promise>, - options: IUseRequestOptions = { immediate: true }, + options: IUseRequestOptions = { immediate: false }, ) { const loading = ref(false) const error = ref(false) 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 }) } - onLoad(() => { - options.immediate && run() - }) + options.immediate && run() return { loading, error, data, run } } diff --git a/src/pages/about/components/request.vue b/src/pages/about/components/request.vue index a8bf509..89a656d 100644 --- a/src/pages/about/components/request.vue +++ b/src/pages/about/components/request.vue @@ -47,6 +47,7 @@ const recommendUrl = ref('http://laf.run/signup?code=ohaOgIX') const initialData = undefined // 适合少部分全局性的接口————多个页面都需要的请求接口,额外编写一个 Service 层 const { loading, error, data, run } = useRequest(() => getFooAPI('菲鸽'), { + immediate: true, initialData, }) const reset = () => {