封装网络请求
import { UseFetchOptions } from "nuxt/app";
type Methods = "GET" | "POST" | "DELETE" | "PUT";
const BASE_URL = "";
export interface IResultData<T> {
code: number;
data: T;
msg: string;
}
class HttpRequest {
request<T = any>(url: string, method: Methods, data: any, options?: UseFetchOptions<T>) {
return new Promise((resolve, reject) => {
const newOptions: UseFetchOptions<T> = {
baseURL: BASE_URL,
method,
...options,
};
if (method === "GET" || method === "DELETE") {
newOptions.params = data;
}
if (method === "POST" || method === "PUT") {
newOptions.body = data;
}
useFetch(url, newOptions)
.then((res) => {
resolve(res.data.value);
})
.catch((error) => {
reject(error);
});
});
}
get<T = any>(url: string, params?: any, options?: UseFetchOptions<T>) {
return this.request(url, "GET", params, options);
}
post<T = any>(url: string, data: any, options?: UseFetchOptions<T>) {
return this.request(url, "POST", data, options);
}
Put<T = any>(url: string, data: any, options?: UseFetchOptions<T>) {
return this.request(url, "PUT", data, options);
}
Delete<T = any>(url: string, params: any, options?: UseFetchOptions<T>) {
return this.request(url, "DELETE", params, options);
}
}
const httpRequest = new HttpRequest();
export default httpRequest;
统一接口管理
import httpRequest from "../service/index";
const getListData = (params: unknown) => {
return httpRequest.get("http://121.36.81.61:8000/getTenArticleList", params);
};
const editListData = (data: unknown) => {
return httpRequest.post("/test", data, {
server: false,
});
};
export { getListData, editListData };
页面使用
<template>
<el-button @click="handleGetData">网络请求</el-button>
</template>
<script lang="ts" setup>
import { getListData } from "../../api/apiHttp";
const handleGetData = async () => {
const result = await getListData("");
console.log(result);
};
</script>