vue3+axios+ts封装

1. 建立以下目录结构

2. 对应文件代码如下

config.ts

  1. 因为公司项目分为开发,测试生产 三种环境。为了避免每次手动更换对应环境的API,我们可以利用vue官网所提供的模式和环境变量去实现。
  2. 如果你不知道 必须去了解噢。链接分享:模式和环境变量 | Vue CLI (vuejs.org) ​​​​​​
  3. 了解之后我想你就明白下面是干嘛的啦!,实在不明白可以私信我 我会出一期文章
let BASE_URL = "";
const TIME_OUT = 10000;
if (process.env.NODE_ENV === "development") {
  BASE_URL = "http://dev";
} else if (process.env.NODE_ENV == "production") {
  BASE_URL = "http://pro";
} else {
  BASE_URL = "http://test";
}
export {BASE_URL, TIME_OUT};

 type.js 忽略 

request/index.ts

import axios from "axios";
// 引入 axios 实例
import type {AxiosInstance} from "axios";
import {ElLoading} from "element-plus";
// 引入 Loading实例
import { LoadingInstance } from 'element-plus/lib/components/loading/src/loading.d.js';

class HYRequest {
  instance: AxiosInstance; //axios实例
  showLoading: boolean; // 是否开启Loading
  loading?: ILoadingInstance; //Loading实例
  constructor(config: HYRequestConfig) {
    this.instance = axios.create(config);
    this.interceptors = config.interceptors;
    this.showLoading = config.showLoading ?? DEAFULT_LOADING;
    //添加拦截器
    this.instance.interceptors.request.use(
      (config) => {
        if (this.showLoading) {
          this.loading = ElLoading.service({
            lock: true,
            text: "正在请求数据...",
            background: "regba(0,0,0,0.5)"
          });
        }
        return config;
      },
      (err) => {
        console.log("所有实例的拦拦截器:请求拦截失败");
        return err;
      }
    );
    this.instance.interceptors.response.use(
      (res) => {
        console.log("所有实例的拦拦截器:响应拦截成功");
        //将loading移除
        this.loading?.close();
        const data = res.data as any;
        if (data.returnCode === "-1001") {
          console.log("请求失败,错误信息");
        } else {
          return data;
        }
      },
      (err) => {
        console.log("所有实例的拦拦截器:响应拦截失败");
        if (err.response.status === 404) {
          console.log("404的错误");
        }
        return err;
      }
    );
  }
	request<T>(config: HYRequestConfig): Promise<T> {
		return new Promise((resolve, reject) => {
			if (config.showLoading === true) {
				this.showLoading = config.showLoading;
			}
			this.instance
				.request<any, any>(config)
				.then(res => {
					this.showLoading = DEAFULT_LOADING;
					resolve(res);
				})
				.catch(err => {
					this.showLoading = DEAFULT_LOADING;
					reject(err);
					return err;
				});
		});
}

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

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

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

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

export default HYRequest;

index.ts

import HYRequest from "./request";
import {BASE_URL, TIME_OUT} from "./request/config";
const hyRequest = new HYRequest({
  baseURL: BASE_URL,
  timeout: TIME_OUT,
});

export default hyRequest;

main.ts

import {createApp} from "vue";
import App from "./App.vue";
import router from "./router";
import {ElButton} from "element-plus/lib/";
import http from "./service/index";
import "element-plus/theme-chalk/index.css";
import store from "./store";
createApp(App)
  .component(ElButton.name, ElButton)
  .use(store)
  .use(router)
  .mount("#app");

http
  .request{
    url: "/home/multidata",
    method: "get",
    showLoading: false
  })
  .then((res) => {});

http
  .get({
    url: "/home/multidata",
    showLoading: false
  })

  • 8
    点赞
  • 27
    收藏
    觉得还不错? 一键收藏
  • 8
    评论
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值