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' import { UnwrapRef } from 'vue'
type IUseRequestOptions<T> = { type IUseRequestOptions<T> = {
/** 是否立即执行如果是则在onLoad执行 */ /** 是否立即执行 */
immediate?: boolean immediate?: boolean
/** 初始化数据 */ /** 初始化数据 */
initialData?: T initialData?: T
@ -11,34 +11,34 @@ type IUseRequestOptions<T> = {
* useRequest是一个定制化的请求钩子 * useRequest是一个定制化的请求钩子
* @param func Promise * @param func Promise
* @param options {immediate, initialData} * @param options {immediate, initialData}
* @param options.immediate true * @param options.immediate false
* @param options.initialData undefined * @param options.initialData undefined
* @returns {loading, error, data, run} * @returns {loading, error, data, run}
*/ */
export default function useRequest<T>( export default function useRequest<T>(
func: () => Promise<IResData<T>>, func: () => Promise<IResData<T>>,
options: IUseRequestOptions<T> = { immediate: true }, options: IUseRequestOptions<T> = { immediate: false },
) { ) {
const loading = ref(false) const loading = ref(false)
const error = ref(false) const error = ref(false)
const data = ref<T>(options.initialData) const data = ref<T>(options.initialData)
const run = async () => { const run = async () => {
loading.value = true loading.value = true
func() return func()
.then((res) => { .then((res) => {
data.value = res.data as UnwrapRef<T> data.value = res.data as UnwrapRef<T>
error.value = false error.value = false
return data.value
}) })
.catch((err) => { .catch((err) => {
error.value = err error.value = err
throw err
}) })
.finally(() => { .finally(() => {
loading.value = false loading.value = false
}) })
} }
onLoad(() => { options.immediate && run()
options.immediate && run()
})
return { loading, error, data, run } return { loading, error, data, run }
} }

View File

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