Skip to content

请求封装

封装$fetch

新建目录结构

bash
├── utils
   ├── http.js

http.js

  • 请求带上 cookie 参数
js
/**
 * @description http模块
 */
// 接口基地址
const BASE_URL = import.meta.env.VITE_BASE_URL;
// 请求拦截器
const requestInterceptor = (config) => {
  const headers = {};
  console.log(config);
  // 增加头部信息
  headers["client-type"] = "web";
  headers["sign"] = "1234567890";
  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;
};
// 错误拦截器
const errorInterceptor = (err) => {
  return Promise.reject(err.error);
};

const httpInstance = $fetch.create({
  baseURL: BASE_URL,
  onRequest: requestInterceptor,
  onResponse: responseInterceptor,
  onRequestError: errorInterceptor,
});

export default httpInstance;

写 api 文件

ts
import httpbox from "@/utils/http";
export function texthomeApibox(params) {
  return httpbox("elecdemo/v1/plan/getList", { params, method: "GET" });
}

页面上使用

  • 渲染数据
ts
import { texthomeApibox } from "@/api/elecdemo/apielecdemo.js";
// 使用
const { data, pending, refresh } = await useAsyncData("homeIndex", async () => {
  const [data1] = await Promise.all([texthomeApibox({ page: 1, size: 10 })]);
  console.log(data1);
  if (data1.code == 200) {
    console.log("接口1获取成功");
  }
  return [data1.data];
});

console.log(data.value[0]);
const dataAll = ref(data.value[0]);
console.log(dataAll.value);
  • 页面上使用
html
<div>{{ dataAll.xxx }}</div>

自己点击按钮触发

ts
/* 赋值结束*/
const handleClick = async () => {
  texthomeApibox({ page: 1, size: 10 }).then((res) => {
    console.log(res);
  });
};