marketingSaaS-front_ui/src/hooks/useRequest.ts

45 lines
1.3 KiB
TypeScript
Raw Normal View History

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