vue3 + typescript + axios封装代码

目录
文章目录隐藏
  1. 1. 对 vue.config.js 进行一系列配置
  2. 2. 在 request.ts 中进行一系列配置
  3. 3. 在 api.ts 中对接口进一步管理
  4. 4. 在 main.ts 中导入请求拦截器 、element-plus
  5. 5. 在 src 下新建 plugs 目录,里新建 element-plus.ts 然后配置下面模块
  6. 6. 在页面按需导入需要用到的 api 接口

vue3 + typescript + axios 封装代码(附带 loading 效果,…并携带跨域处理,…element-plus 按需引入)。

首先,在根目录创建 vue.config.js 里面配置跨域处理。

然后,在 src 下新建 service 目录,在目录中新建两个 ts 文件,一个为 request.ts 另一个为 api.ts。

1. 对 vue.config.js 进行一系列配置

module.exports = {
  // 别名
  configureWebpack: {
    resolve: {
      alias: {
        views: '@/views',
        com: '@/components'
      }
    }
  },
  // 跨域请求
  devServer: {
    // open: false,//
    // host: 'localhost',
    // port: 8080,
    // https: false,
    //以上的 ip 和端口是我们本机的;下面为需要跨域的
    proxy: {
      //配置跨域
      '/api': {
        target: 'http://后台接口地址', //这里后台的地址模拟的;应该填写你们真实的后台接口
        ws: true,
        changOrigin: true, //允许跨域
        pathRewrite: {
          '^/api': '' //请求的时候使用这个 api 就可以
        }
      }
    }
  }
}

2. 在 request.ts 中进行一系列配置

import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios' //导入 axios 和钩子
import { ElLoading } from 'element-plus' //导入 ElLoading
import { ILoadingInstance } from 'element-plus/lib/components/loading/src/loading.type' //导入 ElLoading 钩子
 
// 初始化 loading
 
export class Request {
  public static axiosInstance: AxiosInstance
  public static loading?: ILoadingInstance //loading 实例 挂载到公共的静态属性上 方便获取
 
  public static init() {
    // 创建 axios 实例
    this.axiosInstance = axios.create({
      baseURL: '/api', //转接
      timeout: 6000
    })
    // 初始化拦截器
    this.initInterceptors()
    return axios
  }
 
  // 初始化拦截器
  public static initInterceptors() {
    // 设置 post 请求头
    this.axiosInstance.defaults.headers.post['Content-Type'] =
      'application/x-www-form-urlencoded'
    /**
     * 请求拦截器
     * 每次请求前,如果存在 token 则在请求头中携带 token
     */
 
    this.axiosInstance.interceptors.request.use(
      (config: AxiosRequestConfig) => {
        //  loading 打开
        this.loading = ElLoading.service({
          lock: true,
          text: '正在请求数据...',
          background: 'rgb(0,0,0,0.5)'
        })
 
        const token = localStorage.getItem('ACCESS_TOKEN') //保存 token 到 localStorage 中
        if (token) {
          ;(config as any).headers.Authorization = 'Bearer ' + token //携带请求头
          // ;(config as any).headers.Authorization = sessionStorage.token
        }
        return config
      },
      (error: any) => {
        console.log(error)
      }
    )
 
    // 响应拦截器
    this.axiosInstance.interceptors.response.use(
      // 请求成功
      (response: AxiosResponse) => {
        this.loading?.close() //将 loading 移除
 
        if (response.status === 200) {
          // return Promise.resolve(response.data);
          return response
        } else {
          Request.errorHandle(response)
          // return Promise.reject(response.data);
          return response
        }
      },
      // 请求失败
      (error: any) => {
        const { response } = error
        if (response) {
          // 请求已发出,但是不在 2xx 的范围
          Request.errorHandle(response)
          return Promise.reject(response.data)
        } else {
          // 处理断网的情况
          // eg:请求超时或断网时,更新 state 的 network 状态
          // network 状态在 app.vue 中控制着一个全局的断网提示组件的显示隐藏
          // 关于断网组件中的刷新重新获取数据,会在断网组件中说明
          // message.warn('网络连接异常,请稍后再试!')
          console.log('网络连接异常,请稍后再试!')
        }
      }
    )
  }
 
  /**
   * http 握手错误
   * @param res 响应回调,根据不同响应进行不同操作
   */
  private static errorHandle(res: any) {
    // 状态码判断
    switch (res.status) {
      case 401:
        break
      case 403:
        break
      case 404:
        // message.warn('请求的资源不存在'),
        console.log('请求的资源不存在')
        break
      default:
        // message.warn('连接错误')
        console.log('连接错误')
    }
  }
}

3. 在 api.ts 中对接口进一步管理

import { Request } from './request'//导入请求拦截器 request
 
export function getUserlist(parameter: any) {//导出方法
  return Request.axiosInstance({
    url: '/login',
    method: 'post',
    data: parameter
  })
}

4. 在 main.ts 中导入请求拦截器 、element-plus

import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
 
// 导入请求拦截器
import { Request } from '@/service/request'
import VueAxios from 'vue-axios'
 
//element-plus 按需引入
import 'element-plus/dist/index.css' //局部样式
import { components } from './plugins/element-plus' //局部 js
 
const app = createApp(App)
for (const cpn of components) {
  app.component(cpn.name, cpn)
}
 
app.use(store).use(router).use(VueAxios, Request.init()).mount('#app')

5. 在 src 下新建 plugs 目录,里新建 element-plus.ts 然后配置下面模块

import {
  ElButton,
  ElTable,
  ElAlert,
  ElAside,
  ElAutocomplete,
  ElAvatar,
  ElBacktop,
  ElBadge,
  ElLink,
  ElForm,
  ElFormItem
} from 'element-plus'
export const components = [
  ElButton,
  ElTable,
  ElAlert,
  ElAside,
  ElAutocomplete,
  ElAvatar,
  ElBacktop,
  ElBadge,
  ElLink,
  ElForm,
  ElFormItem
]

6. 在页面按需导入需要用到的 api 接口

<template>
  <div class="home">
    <div>ss</div>
    <img alt="Vue logo" src="../assets/logo.png" />
    <HelloWorld msg="Welcome to Your Vue.js + TypeScript App" />
  </div>
</template>
 
<script lang="ts">
import { defineComponent } from 'vue'
 
import HelloWorld from '@/components/HelloWorld.vue' // @ is an alias to /src
import { getUserlist } from '@/service/api' //接口
export default defineComponent({
  name: 'Home',
  components: {
    //挂载组件
    HelloWorld
  },
  setup() {
    //定义数据 和方法
    getUserlist({ username: 'admin', password: '123456' }).then((res) => {
      console.log(res)
    })
 
    return {}
  }
})
</script>

以上就是关于 vue3 + typescript + axios 封装代码,建议收藏。

「点点赞赏,手留余香」

1

给作者打赏,鼓励TA抓紧创作!

微信微信 支付宝支付宝

还没有人赞赏,快来当第一个赞赏的人吧!

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。
码云笔记 » vue3 + typescript + axios封装代码

发表回复