axios封装loading

封装一个loading,每次加载的时候动态显示加载框;且自动刷新不会影响弹框上传文件的弹框
思路:给config添加headers ,其中自定义一个变量showLoading

import axios from 'axios';
import { getStorage } from './storage';
import { showLoading, hideLoading } from './loading';
import { Message } from 'element-ui';
import qs from 'qs';
import merge from 'lodash/merge';

// eslint-disable-next-line spellcheck/spell-checker
const project = process.env.VUE_APP_PROJECT || 'xxx'; // 默认xxx
class AxiosFetch {
  constructor() {
    axios.interceptors.request.use(params => {
      if (params.headers.showLoading) {
        showLoading();
      }
      // 处理请求数据,如添加Header信息等,
      const config = {
        ...params,
        url: `${params.url}`,
        headers: {
          ...params.headers,
          'Access-Token': getStorage(project + 'token'),
        },
      };
      if (config.method === 'get') {
        config.paramsSerializer = function (params) {
          return qs.stringify(params, { arrayFormat: 'repeat' });
        };
      }
      return config;
    });
    axios.interceptors.response.use(
      response => {
        if (response.config.headers.showLoading) {
          hideLoading();
        }
        // 处理返回数据
        return response.data;
      },
      error => {
        if (error.config.headers.showLoading) {
          hideLoading();
        }
        if (error.response.data && error.response.data.message) {
          Message.error({
            message: error.response.data.message,
          });
        }
        if (error.response.status === 401 || error.response.status === 40003) {
          document.location.href = '/';
        }
        return Promise.reject(error);
      },
    );
  }

  private getConfig(config, loading) {
  	// merge 并集.给config添加headers ,其中自定义一个变量showLoading
    return merge({}, config, { headers: { showLoading: loading } });
  }

  public get(url: string, config: object = {}, loading = true): Promise<any> {
  	// this.getConfig(config, loading) 就是请求拦截器的params 
    return axios.get(url, this.getConfig(config, loading));
  }

  public post(url: string, data: any = {}, config: object = {}, loading = true): Promise<any> {
    return axios.post(url, data, this.getConfig(config, loading));
  }

  public put(url: string, data: any, config: object = {}, loading = true): Promise<any> {
    return axios.put(url, data, this.getConfig(config, loading));
  }

  public delete(url: string, config: object = {}, loading = true): Promise<any> {
    return axios.delete(url, this.getConfig(config, loading));
  }
}

const Fetch = new AxiosFetch();

export default Fetch;

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在Vue 3中使用TypeScript封装axios并包含loading功能的步骤如下: 1. 首先,安装axios和@types/axios依赖: ``` npm install axios @types/axios ``` 2. 创建一个名为api.ts的文件,用于封装axios请求和loading功能: ```typescript import axios, { AxiosRequestConfig, AxiosResponse } from 'axios'; import { reactive } from 'vue'; // 创建一个loading对象,用于控制loading状态 const loading = reactive({ isLoading: false, }); // 创建一个axios实例 const instance = axios.create({ baseURL: 'https://api.example.com', // 设置请求的基础URL timeout: 5000, // 设置请求超时时间 }); // 请求拦截器,在发送请求之前执行 instance.interceptors.request.use( (config: AxiosRequestConfig) => { loading.isLoading = true; // 开启loading状态 return config; }, (error) => { loading.isLoading = false; // 关闭loading状态 return Promise.reject(error); } ); // 响应拦截器,在接收到响应之后执行 instance.interceptors.response.use( (response: AxiosResponse) => { loading.isLoading = false; // 关闭loading状态 return response.data; }, (error) => { loading.isLoading = false; // 关闭loading状态 return Promise.reject(error); } ); // 封装get请求方法 export const get = async <T>(url: string, config?: AxiosRequestConfig): Promise<T> => { try { const response = await instance.get<T>(url, config); return response; } catch (error) { throw new Error(error); } }; // 封装post请求方法 export const post = async <T>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T> => { try { const response = await instance.post<T>(url, data, config); return response; } catch (error) { throw new Error(error); } }; export default { loading, }; ``` 3. 在Vue组件中使用封装axiosloading功能: ```vue <template> <div> <button @click="fetchData">Fetch Data</button> <div v-if="api.loading.isLoading">Loading...</div> <div v-else>{{ data }}</div> </div> </template> <script> import { ref } from 'vue'; import api from './api'; export default { setup() { const data = ref(''); const fetchData = async () => { try { const response = await api.get<string>('/data'); data.value = response; } catch (error) { console.error(error); } }; return { fetchData, data, ...api, }; }, }; </script> ``` 在上述代码中,我们通过`api.ts`文件封装axios的get和post请求方法,并使用`reactive`创建了一个loading对象来控制loading状态。在Vue组件中,我们可以直接调用`api.get`或`api.post`方法来发送请求,并通过`api.loading.isLoading`来控制loading的显示与隐藏。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值