qa_portal_vue/app/composables/useRequest.ts

117 lines
2.8 KiB
TypeScript
Raw Normal View History

2026-03-10 10:13:19 +08:00
/**
* - useFetch
* Loading
*/
import type { UseFetchOptions } from "nuxt/app";
/**
* - Nuxt UseFetchOptions
*/
export type RequestOptions<DataT = any> = UseFetchOptions<DataT, DataT> & {
/** 是否显示加载状态 */
showLoading?: boolean
/** 成功提示信息 */
successMsg?: string
/** 错误提示信息 */
errorMsg?: string
/** 是否手动触发 */
manual?: boolean
}
/**
*
* @param url -
* @param options -
*/
export function useRequest<DataT = any, ErrorT = any>(url: string, options: RequestOptions<DataT> = {}) {
const config = useRuntimeConfig();
const {
// showLoading = false,
successMsg = "",
errorMsg = "",
manual = false,
...restOptions
} = options;
// 计算完整 URL
const fullUrl = computed(() => config.public.apiBaseUrl + url);
// 显示成功提示
const showSuccessTip = (msg: string) => {
if (msg) {
console.log(`[Success] ${msg}`);
}
};
// 显示错误提示
const showErrorTip = (msg: string, err?: any) => {
if (msg || errorMsg) {
const tip = msg || errorMsg || (err as Error)?.message || "请求失败";
console.error(`[Error] ${tip}`, err);
}
};
// 使用 useFetch 发起请求
const { data, error, execute, ...rest } = useFetch<DataT, ErrorT>(fullUrl, {
...restOptions,
// 请求完成后的回调
onResponse({ response }: any) {
if (showSuccessTip && response.ok) {
showSuccessTip(successMsg);
}
},
// 请求出错后的回调
onResponseError({ error }: any) {
showErrorTip(errorMsg, error);
},
} as any);
// 手动执行函数
const run = async () => {
await execute();
return { data: data.value, error: error.value };
};
// 立即执行(如果 manual 为 false
if (!manual) {
void execute();
}
return {
data,
error,
execute: run,
...rest,
};
}
/**
* GET
*/
export function useGet<DataT = any, ErrorT = any>(url: string, options: RequestOptions<DataT> = {}) {
return useRequest<DataT, ErrorT>(url, { ...options, method: "get" });
}
/**
* POST
*/
export function usePost<DataT = any, ErrorT = any>(url: string, options: RequestOptions<DataT> = {}) {
return useRequest<DataT, ErrorT>(url, { ...options, method: "post" });
}
/**
* PUT
*/
export function usePut<DataT = any, ErrorT = any>(url: string, options: RequestOptions<DataT> = {}) {
return useRequest<DataT, ErrorT>(url, { ...options, method: "put" });
}
/**
* DELETE
*/
export function useDelete<DataT = any, ErrorT = any>(url: string, options: RequestOptions<DataT> = {}) {
return useRequest<DataT, ErrorT>(url, { ...options, method: "delete" });
}