|
@@ -1,4 +1,4 @@
|
|
|
-import type { Ref } from 'vue'
|
|
|
|
|
|
|
+import { type Ref, ref } from 'vue'
|
|
|
|
|
|
|
|
interface IUseRequestOptions<T> {
|
|
interface IUseRequestOptions<T> {
|
|
|
/** 是否立即执行 */
|
|
/** 是否立即执行 */
|
|
@@ -7,11 +7,11 @@ interface IUseRequestOptions<T> {
|
|
|
initialData?: T
|
|
initialData?: T
|
|
|
}
|
|
}
|
|
|
|
|
|
|
|
-interface IUseRequestReturn<T> {
|
|
|
|
|
|
|
+interface IUseRequestReturn<T, P> {
|
|
|
loading: Ref<boolean>
|
|
loading: Ref<boolean>
|
|
|
error: Ref<boolean | Error>
|
|
error: Ref<boolean | Error>
|
|
|
data: Ref<T | undefined>
|
|
data: Ref<T | undefined>
|
|
|
- run: () => Promise<T | undefined>
|
|
|
|
|
|
|
+ run: (args: P) => Promise<T | undefined>
|
|
|
}
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
/**
|
|
@@ -22,16 +22,16 @@ interface IUseRequestReturn<T> {
|
|
|
* @param options.initialData 初始化数据,默认为undefined。
|
|
* @param options.initialData 初始化数据,默认为undefined。
|
|
|
* @returns 返回一个对象{loading, error, data, run},包含请求的加载状态、错误信息、响应数据和手动触发请求的函数。
|
|
* @returns 返回一个对象{loading, error, data, run},包含请求的加载状态、错误信息、响应数据和手动触发请求的函数。
|
|
|
*/
|
|
*/
|
|
|
-export default function useRequest<T>(
|
|
|
|
|
- func: () => Promise<T>,
|
|
|
|
|
|
|
+export default function useRequest<T, P>(
|
|
|
|
|
+ func: (args: P) => Promise<T>,
|
|
|
options: IUseRequestOptions<T> = { immediate: false },
|
|
options: IUseRequestOptions<T> = { immediate: false },
|
|
|
-): IUseRequestReturn<T> {
|
|
|
|
|
|
|
+): IUseRequestReturn<T, P> {
|
|
|
const loading = ref(false)
|
|
const loading = ref(false)
|
|
|
const error = ref(false)
|
|
const error = ref(false)
|
|
|
const data = ref<T | undefined>(options.initialData) as Ref<T | undefined>
|
|
const data = ref<T | undefined>(options.initialData) as Ref<T | undefined>
|
|
|
- const run = async () => {
|
|
|
|
|
|
|
+ const run = async (args: P) => {
|
|
|
loading.value = true
|
|
loading.value = true
|
|
|
- return func()
|
|
|
|
|
|
|
+ return func(args)
|
|
|
.then((res) => {
|
|
.then((res) => {
|
|
|
data.value = res
|
|
data.value = res
|
|
|
error.value = false
|
|
error.value = false
|
|
@@ -46,6 +46,8 @@ export default function useRequest<T>(
|
|
|
})
|
|
})
|
|
|
}
|
|
}
|
|
|
|
|
|
|
|
- options.immediate && run()
|
|
|
|
|
|
|
+ if (options.immediate) {
|
|
|
|
|
+ (run as (args: P) => Promise<T | undefined>)({} as P)
|
|
|
|
|
+ }
|
|
|
return { loading, error, data, run }
|
|
return { loading, error, data, run }
|
|
|
}
|
|
}
|