vue3 学习笔记04 -- axios的使用及封装

vue3 学习笔记04 – axios的使用及封装

  • 安装 Axios 和 TypeScript 类型定义
npm install axios
npm install -D @types/axios

创建一个 Axios 实例并封装成一个可复用的模块,这样可以在整个应用中轻松地进行 API 请求管理。

  • 在 src 目录下创建一个 services 文件夹,并在其中创建 api.ts 文件:
  // src/services/api.ts

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

// 创建一个 axios 实例
const api: AxiosInstance = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_API,
  timeout: 30000, // 请求超时时间
  headers: {
    'Content-Type': 'application/json'
    // 其他默认请求头可以在这里配置
  }
});

// 请求拦截器
api.interceptors.request.use(
  (config: AxiosRequestConfig) => {
    // 在请求发送之前做些什么,例如加入 token 等操作
    return config;
  },
  (error) => {
    // 处理请求错误
    return Promise.reject(error);
  }
);

// 响应拦截器
api.interceptors.response.use(
  (response: AxiosResponse) => {
    // 在响应数据返回之前做些什么,例如对响应数据进行处理
    return response.data;
  },
  (error) => {
    // 处理响应错误
    return Promise.reject(error);
  }
);

export default api;

  • 项目根目录新建.env.dev – 开发环境变量
NODE_ENV = 'development'
VITE_APP_BASE_API = '/api'
VITE_APP_TARGET_URL = "https://api.example.com"
  • 项目根目录新建.env.pro – 生产环境变量
NODE_ENV = 'production'
VITE_APP_BASE_API = '/api'
VITE_APP_TARGET_URL = "https://api.example.com"
  • vite.config.ts中配置proxy
export default defineConfig({
  plugins: [vue()],

  server:{
    host: '0.0.0.0', // 允许IP访问
    proxy: {
        [env.VITE_APP_BASE_API]: {
          changeOrigin: true,
          target: env.VITE_APP_TARGET_URL,
          secure: false,
          rewrite: (path) => path.replace(new RegExp(`^${env.VITE_APP_BASE_API}`), '')
        },
      }
  }
})
  • 使用axios封装

    • 在src/api文件下新建login/login.ts文件
          import api from '@/services/api';
          import { AxiosPromise } from "axios";
          import { LoginData, LoginResult } from "./types";
          export function login(data:LoginData):AxiosPromise<LoginResult> {
              return api({
                  url: '/mock/user/login',
                  method: 'post',
                  data
              })
          }
      
    • src/login/types.ts
          export interface LoginData {
              /**
              * 用户名
              */
              username: string;
              /**
              * 密码
              */
              password: string;
          }
          export interface userInfoVo {
              id: number
              name: string
              phone: number
          }
          /**
          * 登录响应
          */
          export interface LoginResult {
              /**
              * token
              */
              token?: string;
              /**
              * 过期时间(单位:毫秒)
              */
              expireAt?: number;
              /**
              * 刷新token
              */
              refreshToken?: string;
              /**
              * 用户信息
              */
              userInfo?: userInfoVo[];
          }
      
  • vue文件中使用

<template>
 form表单.....
<el-button class="login-button" type="primary" @click="handleLogin" :loading="loading"
        >登录</el-button
      >
</template> 
<script setup lang="ts">
import { login } from '@/api/login/login'
import { useRouter } from 'vue-router'
let loading = ref(false)
const router = useRouter()
const handleLogin = ()=>{
    let data = {
        username:'xxx',
        password:'xxx'
    }
    loading.value = true
    login(data).then((res)=>{
        loading.value = false
        // 一些存储token及其他信息的处理的处理
        ....要干的事
        router.push('/')
    })
}
</script>  

相关推荐

  1. vue3 学习笔记04 -- axios使用封装

    2024-07-11 20:32:03       24 阅读
  2. vue3 学习笔记06 -- pinia简单使用

    2024-07-11 20:32:03       28 阅读
  3. Vue3 Hooks函数使用封装

    2024-07-11 20:32:03       48 阅读
  4. vue3 axios二次封装

    2024-07-11 20:32:03       59 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-11 20:32:03       67 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-11 20:32:03       71 阅读
  3. 在Django里面运行非项目文件

    2024-07-11 20:32:03       58 阅读
  4. Python语言-面向对象

    2024-07-11 20:32:03       69 阅读

热门阅读

  1. 大模型融入云平台,信息化走向数智化

    2024-07-11 20:32:03       19 阅读
  2. 开源项目有哪些机遇与挑战?

    2024-07-11 20:32:03       21 阅读
  3. 精通 mysqldumpslow:深度分析 MySQL 慢查询日志

    2024-07-11 20:32:03       21 阅读
  4. 定个小目标之刷LeetCode热题(41)

    2024-07-11 20:32:03       18 阅读
  5. 详细介绍一下TypeScript

    2024-07-11 20:32:03       22 阅读
  6. Ant-Vue——modal对话框

    2024-07-11 20:32:03       23 阅读
  7. windows 修改 npmrc

    2024-07-11 20:32:03       22 阅读
  8. Python图形用户界面的文本文件加密工具

    2024-07-11 20:32:03       26 阅读
  9. [QT入门]树形视图控件

    2024-07-11 20:32:03       22 阅读
  10. Redis事件和整体框架

    2024-07-11 20:32:03       21 阅读
  11. House holder reflections and Givens rotations

    2024-07-11 20:32:03       20 阅读
  12. Python开发 ——循环中的 `continue` 语句

    2024-07-11 20:32:03       21 阅读