axios配合vant的封装(TS版)

import { Toast } from "vant"
import type { ToastWrapperInstance } from "vant/es/toast/types"
import axios, { AxiosError } from "axios"
import type { AxiosInstance } from "axios"

import { localCache } from "@/utils"
import type { IResponseData, ZJRequestConfig } from "@/services/types"

class ZJRequest {
    request: AxiosInstance
    count: number
    loadingToast?: ToastWrapperInstance

    constructor(config?: ZJRequestConfig) {
        this.count = 0
        this.request = axios.create(config)
        // 添加请求拦截器
        this.request.interceptors.request.use(
            async (interceptorsConfig: ZJRequestConfig) => {
                this.count += 1
                this.loadingToast = Toast.loading({
                    duration: 0,
                    message: "加载中...",
                    forbidClick: true,
                })
                const token = localCache.getCache("token")
                if (token) {
                    if (interceptorsConfig.headers) {
                        interceptorsConfig.headers["Authorization"] = token
                    }
                }
                return interceptorsConfig
            },
            (error) => {
                this.count -= 1
                return Promise.resolve(error)
            }
        )

        // 添加响应拦截器
        this.request.interceptors.response.use(
            (response) => {
                this.count -= 1
                if (this.count <= 0) {
                    this.loadingToast?.clear()
                    this.count = 0 // 防止过快地请求导致一些不必要的错误
                }
                const res: IResponseData = response.data
                // 判断状态
                if (res.code !== 0) {
                    // const errorMsg = "操作失败:" + response.data.msg
                    if (res.code === 20001) {
                        // token不合法,清除token
                        localCache.removeCache("token")
                    } else {
                        // 普通错误消息
                        Toast.fail(res.msg)
                    }
                }
                return response.data
            },
            (error: AxiosError) => {
                this.count -= 1
                if (this.count <= 0) {
                    this.loadingToast?.clear()
                    this.count = 0
                }
                const err: IResponseData = {
                    code: -1,
                    msg: error.message,
                    data: error,
                }
                Toast.fail("请求失败" + error.message)
                return Promise.resolve(err)
            }
        )
    }

    get<D>(config: ZJRequestConfig) {
        const { url = "", ...realConfig } = config
        return this.request.get<any, D>(url, realConfig)
    }

    post<D>(config: ZJRequestConfig) {
        const { url = "", data = {}, ...realConfig } = config
        return this.request.post<any, D>(url, data, realConfig)
    }

    put<D>(config: ZJRequestConfig) {
        const { url = "", data = {}, ...realConfig } = config
        return this.request.put<any, D>(url, data, realConfig)
    }

    delete<D>(config: ZJRequestConfig) {
        const { url = "", ...otherConfig } = config
        return this.request.delete<any, D>(url, otherConfig)
    }
}

export default ZJRequest
import ZJRequest from "@/services/request"

const zjRequest = new ZJRequest({
    baseURL: "/api/client",
    timeout: 100000,
})
export default zjRequest
import zjRequest from "@/services"

// 注册
export const register = (data: any) => {
    return zjRequest.post<API.IResult_Empty>({
        url: "/account/register",
        data,
    })
}
// 登录
export const login = (data: any) => {
    return zjRequest.post<API.IResult_Login>({
        url: "/account/login",
        data,
    })
}
// 退出登录
export const logout = () => {
    return zjRequest.post<API.IResult_Empty>({
        url: "/account/logout",
    })
}
// 修改个人信息
export const updateAccountInfo = (data: any) => {
    return zjRequest.post<API.IResult_Empty>({
        url: "/account/update",
        data,
    })
}

API是一个namespace,大致结构长这样:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以参考以下步骤: 1. 首先安装 axios 和 qs(如果需要) 2. 在 main.js 中引入 axios 并进行二次封装: ``` import axios from 'axios' import qs from 'qs' axios.defaults.baseURL = 'http://api.xxx.com' // 设置接口基地址 axios.defaults.timeout = 10000 // 设置超时时间 axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8' // 设置默认请求头 axios.interceptors.request.use(config => { // 在请求发送之前做一些处理 config.headers.token = localStorage.getItem('token') || '' return config }, error => { // 出错处理 return Promise.reject(error) }) axios.interceptors.response.use(response => { // 在响应成功处理之前做一些处理 return response }, error => { // 响应错误处理 return Promise.reject(error) }) function get (url, params) { return new Promise((resolve, reject) => { axios.get(url, { params }).then(res => { resolve(res.data) }).catch(err => { reject(err.data) }) }) } function post (url, data) { return new Promise((resolve, reject) => { axios.post(url, qs.stringify(data)).then(res => { resolve(res.data) }).catch(err => { reject(err.data) }) }) } export default { get, post } ``` 3. 在组件中使用二次封装后的 axios: ``` import request from '@/utils/request' methods: { getData () { request.get('/api/getData', { id: '123456' }).then(res => { console.log(res) }).catch(err => { console.log(err) }) } } ``` 以上是对于vue3 + vant + ts 配置axios的二次封装的一种实现,仅供参考。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值