使用自定义封装插件(推荐)
安装包
bash
npm install nuxt-custom-fetch
# or
yarn add nuxt-custom-fetch
# or
pnpm add nuxt-custom-fetch
挂载
- nuxt.config.js
bash
export default defineNuxtConfig({
modules: ['nuxt-custom-fetch']
})
封装开始
- http.js
js
// 接口基地址
const BASE_URL = import.meta.env.VITE_BASE_URL;
// 请求拦截器
const requestInterceptor = (config) => {
const headers = {};
console.log(config);
// 增加头部信息
headers["client-type"] = "web";
headers["sign"] = "123456";
headers["access-token"] = useCookie("access_token").value;
config.options.headers = headers;
return config;
};
// 响应拦截器
const responseInterceptor = (response) => {
const res = response.response;
if (res._data.code === 200) {
return res._data;
} else if (res._data.code === 401) {
// token过期或失效
// 清空用户信息
// 当前接口需要权限的话,登录失效即跳转登录页
// jumpToLogin();
return res._data;
} else if (res._data.code === 400) {
return res._data;
}
return res._data;
};
// Create a new instance with configuration
const httpInstance = new CustomFetch({
baseURL: BASE_URL, // Base URL for all requests
immutableKey: false, // If true, only use URL for key generation (default: false)
showLogs: true, // Show request logs (default: false in prod, true in dev)
// Request handling
useHandler: true, // Whether to use the handler function (default: true)
handler: undefined, // Transform params/query before sending
onRequest: requestInterceptor,
onResponse: responseInterceptor,
onRequestError: undefined,
onResponseError: undefined, // When response error occurs
// Offline handling
offline: undefined, // Called when device is offline
});
export default httpInstance;
使用
api.js
js
import http from "@/utils/http";
// 第一种写法
export function getHomeListApi(params) {
return http.get("elecdemo/v1/plan/getList", { params });
}
// 第二种写法
export function getHomeListApi(params) {
return http.request("elecdemo/v1/plan/getList", { params, method: "GET" });
}
页面使用
html
<script setup>
import { getHomeListApi } from '@/api/elecdemo/apielecdemo.js';
// 第一个接口;
const firstValue = async () => {
const { data, error, refresh } = await getHomeListApi({
size: 10,
page: 1
});
return data;
};
// 第二个接口
const secondValue = async () => {
const { data, error, refresh } = await getHomeListApi({
size: 10,
page: 1
});
return data;
};
// 获取第一个数据
const data1 = await firstValue();
// 获取第二个数据
const data2 = await secondValue();
const dataAll = ref(data1.value.data);
const dataAll2 = ref(data2.value.data);
console.log(dataAll.value); // 这样做服务器渲染daataAll的数据
console.log(dataAll2.value); // 这样做服务器渲染daataAll2的数据
// 单独事件
const handleClick = async () => {
const { data, error, refresh } = await getHomeListApi({
size: 10,
page: 1
});
console.log(data.value);
console.log(data.value.msg);
};
</script>