Vue3中使用typescript封装axios的实例详解

这个axios封装,因为是用在vue3的demo里面的,为了方便,在vue3的配置里面按需加载element-plus

封装axios

http.ts

import axios, { AxiosRequestConfig, AxiosRequestHeaders, AxiosResponse } from 'axios'
import { IResponseData } from '@/types'
import { ElMessage, ElLoading, ILoadingInstance } from 'element-plus'

type TAxiosOption = {
  baseURL: string;
  timeout: number;
}

const config = {
  baseURL: '/',
  timeout: 120000
}

let loading: ILoadingInstance;

class Http {
  // service: AxiosInstance;
  service;
  constructor(config: TAxiosOption) {
    this.service = axios.create(config)

    /* 请求拦截  this.service.interceptors.request.use(config => config, error => Promise.reject(error))*/
    this.service.interceptors.request.use((config: AxiosRequestConfig) => {
      /* 业务逻辑
      1. 开启全屏loading动画
      2. 数据加密config.data
      3. 请求头加上token,结合vuex或localstorage:
          if(store.getters.token) config.headers['x-token'] = store.getters.token
          else 重定向
      4. ……
      */
      loading = ElLoading.service({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(255, 255, 255, 0.7)',
      })

      if (localStorage.getItem('token')) {
        (config.headers as AxiosRequestHeaders).authorization = localStorage.getItem('token') as string
      }

      return config
    }, error => {
      /* 请求错误 
      1. 关闭全屏loading动画
      2. 重定向到错误页
      */
      loading.close()
      return Promise.reject(error) // 为了可以在代码中catch到错误信息
    })


    /* 响应拦截   this.service.interceptors.response.use(response => response.data, error => Promise.reject(error))*/
    this.service.interceptors.response.use((response: AxiosResponse) => {
      /* 
      1. 关闭全屏loading动画
      2. 数据解密
      3. 根据 response.data.code 做不同的错误处理
      4. ……
      */
      loading.close()

      const data = response.data
      const { code } = data

      if (code !== '000000') {
        ElMessage.error(data.message)
        return Promise.reject(data)
      }
      return response.data
    }, error => {
      loading.close()
      ElMessage.error('请求失败',)
      return Promise.reject(error)
    })
  }
  get(url: string, params?: object, _object = {}): Promise> {
    return this.service.get(url, { params, ..._object })
  }
  post(url: string, params?: object, _object = {}): Promise> {
    return this.service.post(url, params, _object)
  }
  put(url: string, params?: object, _object = {}): Promise> {
    return this.service.put(url, params, _object)
  }
  delete(url: string, params?: any, _object = {}): Promise> {
    return this.service.delete(url, { params, ..._object })
  }
}

export default new Http(config)

types/index.ts: 接口返回数据的类型定义

export interface IResponseData {
  status: number;
  message?:string;
  data:T;
  code: string;
}

axios的使用

list.vue:

const { data } = await http.get('/goods/list', queryForm.value) list.value = data.list



types/goods.ts

export interface IGoodInfo {
  _id: string;
  goodName: string;
  count: string;
  des: string
}

export interface IList {
  list: IGoodInfo[]
}

到此这篇关于使用typescript封装axios的文章就介绍到这了,更多相关typescript封装axios内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

你可能感兴趣的