import { ref } from 'vue' import { HTTP_CODE } from '@/enums' import type { Response } from '@/http/http' /** * @template ReturnData 返回的数据 * @template Params http请求中需要向后台发送的参数 * @param {异步请求函数} asyncFn * @param {Params} [query] * @example1 * type Result = {"activity": "Do yoga","type": "recreational" "accessibility": 0.9} type Query = { participants: number } * const getConfig = (data: Query) => request({ url: 'https://www.boredapi.com/api/activity' }) const { loaded, result, error } = useRequest(getConfig, { participants: 1 }) @example2 *const getConfig = () => request({ url: 'static/offline/JSON/config.json' }) const { loaded, result, error } = useRequest(getConfig) */ export const useRequest = (asyncFn: (params?: Params) => Promise>, query?: Params) => { const error = ref() const result = ref() const loaded = ref(false) asyncFn(query) .then(({ code, data, msg }) => { if (code === HTTP_CODE.ERR_OK) { result.value = data } else { error.value = msg } }) .catch(err => { error.value = err }) .finally(() => { loaded.value = true }) return { result, loaded, error } }