2 changed files with 6 additions and 43 deletions
@ -1,40 +0,0 @@ |
|||
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<Result, Query>(getConfig, { participants: 1 }) |
|||
@example2 |
|||
*const getConfig = () => request({ url: 'static/offline/JSON/config.json' }) |
|||
const { loaded, result, error } = useRequest<Result>(getConfig) |
|||
*/ |
|||
export const useRequest = <ReturnData = any, Params = any>(asyncFn: (params?: Params) => Promise<Response<ReturnData>>, query?: Params) => { |
|||
const error = ref() |
|||
const result = ref<ReturnData>() |
|||
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 } |
|||
} |
|||
Loading…
Reference in new issue