Merge pull request #107 from JinliangYan/feature/enhance&refine-userequest-hook

Feature/enhance&refine userequest hook
This commit is contained in:
菲鸽 2024-06-11 11:01:50 +08:00 committed by GitHub
commit a7d808f5d3
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 8 additions and 7 deletions

View File

@ -1,7 +1,7 @@
import { UnwrapRef } from 'vue'
type IUseRequestOptions<T> = {
/** 是否立即执行如果是则在onLoad执行 */
/** 是否立即执行 */
immediate?: boolean
/** 初始化数据 */
initialData?: T
@ -11,34 +11,34 @@ type IUseRequestOptions<T> = {
* 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<T>(
func: () => Promise<IResData<T>>,
options: IUseRequestOptions<T> = { immediate: true },
options: IUseRequestOptions<T> = { immediate: false },
) {
const loading = ref(false)
const error = ref(false)
const data = ref<T>(options.initialData)
const run = async () => {
loading.value = true
func()
return func()
.then((res) => {
data.value = res.data as UnwrapRef<T>
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 }
}

View File

@ -47,6 +47,7 @@ const recommendUrl = ref('http://laf.run/signup?code=ohaOgIX')
const initialData = undefined
// Service
const { loading, error, data, run } = useRequest<IFooItem>(() => getFooAPI('菲鸽'), {
immediate: true,
initialData,
})
const reset = () => {