1.新建文件夹service/inde.ts
import { UseFetchOptions } from "nuxt/app";
type Methods = "GET" | "POST" | "DELETE" | "PUT";
const BASE_URL = "http://127.0.0.1:6789/api/";
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: 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);
})
.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;
2.使用配置文件新建请求 新建文件api/index.ts
import httpRequest from "../service/index";
const getDepartmentList = () => {
return httpRequest.get('getDepartmentList',"");
};
const loginApi=(data:any)=>{
return httpRequest.post('login',data)
}
export {
getDepartmentList,
loginApi
};
3.在页面中使用
const getList = async () => {
const res: any = await getDepartmentList();
console.log("结果", res.data.value.departmentList[0].departmentName);
results.value = res.data.value.departmentList[0].departmentName;
};