vue3+ ts axios封装

// 引入 axios 实例
import axios from "axios";
import { AxiosInstance, CreateAxiosDefaults, AxiosRequestConfig ,AxiosResponse } from "axios";
import { ElLoading } from "element-plus";
// 引入 Loading实例
import { LoadingInstance } from 'element-plus/lib/components/loading/src/loading.d.js';
import qs from "qs"
import { useUser } from '@/store/user';
const {userInfo} = useUser()
type RequestConfig = {
  interceptors?: { request: { use: () => {} } }
  showLoading?: boolean,
  method?: string
} & AxiosRequestConfig
class Http {
  instance: AxiosInstance;
  showLoading: boolean;
  loading?: LoadingInstance; //element Loading
  interceptors?: any
  constructor(config: RequestConfig) {
    this.instance = axios.create(config);
    this.interceptors = config.interceptors;
    this.showLoading = config.showLoading ?? false;
    //请求拦截
    this.instance.interceptors.request.use(
      (config) => {
        config.params={'_':Date.now(),...config.params};
        if (this.showLoading) {
          this.loading = ElLoading.service({
            lock: true,
            text: "加载中...",
          });
        }
        if (
          config.method?.toLocaleUpperCase() === 'POST' 
        ) {
          config.data = qs.stringify(config.data)
        }
        config.headers['token']=userInfo.data?.token
        return config;
      },
      (err) => {
        return err;
      }
    );

    //响应拦截
    this.instance.interceptors.response.use(
      (res:AxiosResponse) => {
        this.loading?.close();
        if (res.data.code != "success") {
          return Promise.reject({msg:'接口数据错误',data:res.data})
        } else {
          return res.data;
        }
      },
      (err) => {
        this.loading?.close();
          return err;
      }
    );
  }
  request<T>(config: RequestConfig): Promise<T> {
    this.showLoading = Boolean(config.showLoading ?? this.loading);
    return this.instance.request<any, any>(config)
   
  }

  get<T>(config: RequestConfig): Promise<T> {
    return this.request<T>({ ...config, method: "get" });
  }

  post<T>(config: RequestConfig): Promise<T> {
    return this.request<T>({ ...config, method: "post" });
  }

}

export default new Http({
  baseURL: "/",
  timeout: 10000,
});
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值