Nuxt3已经为我们提供了 $fetch 直接用就好
- 首先在目录utils下创建 api.js 跟 request.js 两个文件,api文件是用来写具体的接口函数的,request是用来二次封装 $fetch 以达到适配我们项目的需要。
- 以下是我的request.js封装代码,可按需要修改
export const apiUse = async (url, method, options) => {
const nuxtApp = useNuxtApp();
const runConfig = useRuntimeConfig();
const baseUrl = runConfig.public.baseUrl;
const reqUrl = baseUrl + url;
options = {
method,
headers: {
"Content-Type": "application/json",
},
body: {
...options,
token: "",
platform: "h5",
language: nuxtApp.$i18n.locale.value,
},
};
const {
data,
error
} = await useFetch(reqUrl, options);
if (error.value) {
return error.value;
} else {
return data.value;
}
};
export const asyncFetchData = async (url, method, options) => {
const nuxtApp = useNuxtApp();
const runConfig = useRuntimeConfig();
const baseUrl = runConfig.public.baseUrl;
const reqUrl = baseUrl + url;
const key = url.split('/')[url.split('/').length - 1]
const {
data,
pending,
error,
refresh
} = await useAsyncData(key, () => $fetch(reqUrl, {
method,
headers: {
"Content-Type": "application/json",
},
body: {
...options,
token: "",
platform: "h5",
language: nuxtApp.$i18n.locale.value,
},
}));
return {
data,
pending,
error,
refresh
};
}
export const fGET = (url, params) => {
return apiUse(url, "GET", params);
};
export const fPOST = (url, params) => {
return apiUse(url, "POST", params);
};
export const fPUT = (url, params) => {
return apiUse(url, "put", params);
};
export const fDELETE = (url, params) => {
return apiUse(url, "delete", params);
};
export const GET = (url, params) => {
return asyncFetchData(url, 'GET', params);
};
export const POST = (url, params) => {
return asyncFetchData(url, "POST", params);
};
export const PUT = (url, params) => {
return asyncFetchData(url, "put", params);
};
export const DELETE = (url, params) => {
return asyncFetchData(url, "delete", params);
};
- 以下是我的api.js封装代码,可按需要修改
import {
GET,
POST,
PUT,
DELETE,
fGET,
fPOST,
fPUT,
fDELETE,
} from "./request"
export const getNotice = (params) => {
return POST('/sale/info/detail', params)
}
- 页面中使用接口方法
getNotice({
id: 1
}).then((res) => {
const {
data,
error
} = res
if (error) {
console.log(error.value)
}else{
console.log(data.value)
}
})