unibest/src/hooks/useRequest.ts

45 lines
1.3 KiB
TypeScript
Raw Normal View History

2024-05-20 08:52:02 +08:00
import { UnwrapRef } from 'vue'
2024-04-17 15:32:15 +08:00
type IUseRequestOptions<T> = {
/** 是否立即执行 */
2024-04-17 15:32:15 +08:00
immediate?: boolean
/** 初始化数据 */
initialData?: T
}
/**
* useRequest是一个定制化的请求钩子
* @param func Promise
* @param options {immediate, initialData}
* @param options.immediate false
2024-04-17 15:32:15 +08:00
* @param options.initialData undefined
* @returns {loading, error, data, run}
*/
export default function useRequest<T>(
func: () => Promise<IResData<T>>,
options: IUseRequestOptions<T> = { immediate: false },
2024-04-17 15:32:15 +08:00
) {
const loading = ref(false)
const error = ref(false)
2024-05-20 08:52:02 +08:00
const data = ref<T>(options.initialData)
2024-04-17 15:32:15 +08:00
const run = async () => {
loading.value = true
return func()
2024-04-17 15:32:15 +08:00
.then((res) => {
2024-05-20 08:52:02 +08:00
data.value = res.data as UnwrapRef<T>
2024-04-17 15:32:15 +08:00
error.value = false
return data.value
2024-04-17 15:32:15 +08:00
})
.catch((err) => {
error.value = err
throw err
2024-04-17 15:32:15 +08:00
})
.finally(() => {
loading.value = false
})
}
options.immediate && run()
2024-04-17 15:32:15 +08:00
return { loading, error, data, run }
}