vue3 +ts 如何安装封装axios

在这里插入图片描述


以vite创建的项目,vue3使用axios。
使用ts二次封装axios访问接口,并调用接口。

vue3安装封装axios,其实和vue2的大差不差。只是在ts和js上,有些区别。

为什么封装axios

  1. 求头能统一处理
  2. 便于接口的统一管理
  3. 解决回调地狱
  4. 配置拦截器,给不同的实例配置不同的拦截器,支持以对象形式接受多个拦截器配置

安装axios

npm install axios

引入插件

在使用的文件中引入

import axios from "axios";

封装request

先在 src 下创建一个 utils文件夹,并添加一个 request.ts 文件

import axios, {
    
     AxiosInstance, AxiosRequestConfig } from 'axios'

class HttpRequest {
    
    
    private readonly baseUrl: string;
    constructor() {
    
    
        this.baseUrl = 'http://localhost:8080'
    }
    getInsideConfig() {
    
    
        const config = {
    
    
            baseURL: this.baseUrl,// 所有的请求地址前缀部分(没有后端请求不用写)  
            timeout: 80000, // 请求超时时间(毫秒)
            withCredentials: true,// 异步请求携带cookie
            // headers: {
    
    
            // 设置后端需要的传参类型
            // 'Content-Type': 'application/json',
            // 'token': x-auth-token',//一开始就要token
            // 'X-Requested-With': 'XMLHttpRequest',
            // },
        }
        return config
    }

    // 请求拦截
    interceptors(instance: AxiosInstance, url: string | number | undefined) {
    
    
        instance.interceptors.request.use(config => {
    
    
            // 添加全局的loading..
            // 请求头携带token
            return config
        }, (error: any) => {
    
    
            return Promise.reject(error)
        })
        //响应拦截
        instance.interceptors.response.use(res => {
    
    
            //返回数据
            const {
    
     data } = res
            console.log('返回数据处理', res)
            return data
        }, (error: any) => {
    
    
            console.log('error==>', error)
            return Promise.reject(error)
        })
    }

    request(options: AxiosRequestConfig) {
    
    
        const instance = axios.create()
        options = Object.assign(this.getInsideConfig(), options)
        this.interceptors(instance, options.url)
        return instance(options)
    }
}

const http = new HttpRequest()
export default http

封装接口

在api的文件夹中,新建一个api的ts文件。

注意:​​因为get请求的参数需要params,它是即将与请求一起发送的 URL 参数,为了简写采用了ES6的解构,就是把下面的 params 解构,只有get 请求需要加多一层params

其它请求,如 post 等请求等就不用解构,形参是什么都行。

案例

src文件夹下新建api文件夹,新建api.ts文件,里面写你请求后台的接口,比如我这里的请求地址是/test, 加上axios的baseURL,完整的请求路径就是http://localhost:8080/test

import http from '../utils/request'
//get有值
export function getTest(params: any) {
    
    
  return http.request({
    
    
    url: '/test',
    method: 'get',
    params
  })
}

//get无值
export function (params: any) {
    
    
  return http.request({
    
    
    url: '/test',
    method: 'get',
    params
  })
}

使用

请求的组件上使用

import {
    
     ref, onMounted } from "vue";
import {
    
     getFileList } from "../../api/index";

export default {
    
    
  setup() {
    
    
    onMounted(() => {
    
    
      getTest().then((res: any) => {
    
    
        console.log(res);
      });
    });
  },
};

猜你喜欢

转载自blog.csdn.net/weixin_48998573/article/details/129950675