diff --git a/src/hooks/useRequest.ts b/src/hooks/useRequest.ts index 9cc392b..0559276 100644 --- a/src/hooks/useRequest.ts +++ b/src/hooks/useRequest.ts @@ -1,3 +1,5 @@ +import { UnwrapRef } from 'vue' + type IUseRequestOptions = { /** 是否立即执行,如果是则在onLoad执行 */ immediate?: boolean @@ -19,12 +21,12 @@ export default function useRequest( ) { const loading = ref(false) const error = ref(false) - const data = ref() + const data = ref(options.initialData) const run = async () => { loading.value = true func() .then((res) => { - data.value = res.data + data.value = res.data as UnwrapRef error.value = false }) .catch((err) => { diff --git a/src/pages/about/components/request.vue b/src/pages/about/components/request.vue index 1ca55bd..a8bf509 100644 --- a/src/pages/about/components/request.vue +++ b/src/pages/about/components/request.vue @@ -24,9 +24,14 @@ 发送请求 - 请求数据如下 - {{ JSON.stringify(data) }} - 清除数据 + + loading... + + 请求数据如下 + {{ JSON.stringify(data) }} + + + 重置数据 @@ -35,9 +40,16 @@ import { getFooAPI, postFooAPI, IFooItem } from '@/service/index/foo' const recommendUrl = ref('http://laf.run/signup?code=ohaOgIX') +// const initialData = { +// name: 'initialData', +// id: '1234', +// } +const initialData = undefined // 适合少部分全局性的接口————多个页面都需要的请求接口,额外编写一个 Service 层 -const { loading, error, data, run } = useRequest(() => getFooAPI('菲鸽')) +const { loading, error, data, run } = useRequest(() => getFooAPI('菲鸽'), { + initialData, +}) const reset = () => { - data.value = undefined + data.value = initialData }