vue+ts下对axios的封装实现

yizhihongxing

下面就详细讲解“vue+ts下对axios的封装实现”的完整攻略:

一、安装Axios

首先,在项目根目录下执行以下命令安装axios和@types/axios:

npm install axios @types/axios --save

安装完成后,在vue项目中引入axios:

import Axios from 'axios';

二、创建axios实例

我们可以通过自定义配置来创建axios实例。

在src/api目录下,新建Api.ts文件。在文件中通过axios.create()方法来创建一个axios实例,然后对它进行一些自定义设置。

import Axios, { AxiosInstance } from 'axios';

const api: AxiosInstance = Axios.create({
  timeout: 10000, //超时时间
  baseURL: '/api',
  headers: {
    'Content-Type': 'application/json; charset=UTF-8',
    //其他头部信息...
  }
});

export default api;

我们设置了超时时间、基础URL、请求头等信息。

三、定义接口请求方法

在src/api目录下,创建一个ApiConfig.ts文件,并在文件中定义所有的接口请求方法。

import { AxiosResponse, AxiosError } from 'axios';
import api from './Api';

interface Result {
  code: number;
  data?: any;
  message?: string;
}

class ApiConfig {
  public static post(url: string, data: any): Promise<Result> {
    return new Promise((resolve, reject) => {
      api.post(url, data)
        .then((response: AxiosResponse<Result>) => {
          resolve(response.data);
        })
        .catch((error: AxiosError) => {
          reject(error.message);
        });
    });
  }

  public static get(url: string, params?: any): Promise<Result> {
    return new Promise((resolve, reject) => {
      api.get(url, { params: params })
        .then((response: AxiosResponse<Result>) => {
          resolve(response.data);
        })
        .catch((error: AxiosError) => {
          reject(error.message);
        });
    });
  }
}

export default ApiConfig;

如上述代码所示,我们定义了两个方法:post和get,通过访问api实例,并返回Promise实例来执行我们的请求。

四、调用Api

我们可以在Vue组件中直接使用ApiConfig的post和get方法,来调用我们所定义的接口请求方法。一个简单的例子如下:

import { Component, Vue } from 'vue-property-decorator';
import ApiConfig from '@/api/ApiConfig';

@Component({})
export default class HelloWorld extends Vue {
  private async postRequest(): Promise<void> {
    try {
      const response = await ApiConfig.post('/some-url', { data: 'some data' });
      console.log('response:', response);
    } catch (error) {
      console.error('error:', error);
    }
  }

  private async getRequest(): Promise<void> {
    try {
      const response = await ApiConfig.get('/some-url', { params: { data: 'some data' } });
      console.log('response:', response);
    } catch (error) {
      console.error('error:', error);
    }
  }
}

五、使用示例

示例1:获取用户信息

import { AxiosResponse, AxiosError } from 'axios';
import api from '@/api/Api';

interface User {
  username: string;
  password: string;
}

interface Result {
  code: number;
  data?: User;
  message?: string;
}

class UserApi {
  public static getUser(id: number): Promise<Result> {
    return new Promise((resolve, reject) => {
      api.get(`/users/${id}`)
        .then((response: AxiosResponse<Result>) => {
          resolve(response.data);
        })
        .catch((error: AxiosError) => {
          reject(error.message);
        });
    });
  }
}

export default UserApi;

在Vue组件中使用示例:

import { Component, Vue } from 'vue-property-decorator';
import UserApi from '@/api/UserApi';

@Component({})
export default class UserDetail extends Vue {
  private userId: number = 1;
  private user: User | undefined = undefined;

  private async mounted() {
    try {
      const response = await UserApi.getUser(this.userId);
      if (response.code === 200) {
        this.user = response.data;
      } else {
        console.error('failed to get user');
      }
    } catch (error) {
      console.error('failed to get user', error);
    }
  }
}

示例2:添加新用户

import { AxiosResponse, AxiosError } from 'axios';
import api from '@/api/Api';

interface User {
  username: string;
  password: string;
}

interface Result {
  code: number;
  data?: any;
  message?: string;
}

class UserApi {
  public static addUser(user: User): Promise<Result> {
    return new Promise((resolve, reject) => {
      api.post(`/users`, user)
        .then((response: AxiosResponse<Result>) => {
          resolve(response.data);
        })
        .catch((error: AxiosError) => {
          reject(error.message);
        });
    });
  }
}

export default UserApi;

在Vue组件中使用示例:

import { Component, Vue } from 'vue-property-decorator';
import UserApi from '@/api/UserApi';

@Component({})
export default class CreateUser extends Vue {
  private user: User = { username: '', password: '' };

  private async saveUser(): Promise<void> {
    try {
      const response = await UserApi.addUser(this.user);
      if (response.code === 200) {
        console.log('success');
      } else {
        console.error('failed to add user');
      }
    } catch (error) {
      console.error('failed to add user', error);
    }
  }
}

以上就是“vue+ts下对axios的封装实现”的完整攻略。

本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:vue+ts下对axios的封装实现 - Python技术站

(0)
上一篇 2023年5月28日
下一篇 2023年5月28日

相关文章

  • vue中设置滚动条方式

    我来给您详细讲解一下vue中设置滚动条方式的完整攻略,以下是具体步骤: 1. 引入第三方滚动条库 Vue原生并不提供滚动条相关的API,因此我们需要借助第三方库来添加滚动条组件。这里我推荐使用perfect-scrollbar,这是一个轻量级的滚动条插件,使用简单。 我们可以在项目中使用npm安装该插件: npm install perfect-scroll…

    Vue 2023年5月29日
    00
  • Vue按时间段查询数据组件使用详解

    关于“Vue按时间段查询数据组件使用详解”的完整攻略,我来详细讲解如下: 一、背景 在开发Web应用程序时,常常需要按时间段查询数据。如果每个查询功能都自己写一遍,那代码量会非常庞大,而且不利于维护和更新。为了更高效地开发查询功能,本文将介绍一种Vue组件的开发,该组件可以根据指定的时间段来查询数据。 二、组件设计 我们将设计一个“按时间段查询数据”的Vue…

    Vue 2023年5月29日
    00
  • Vue自定义指令详细

    Vue自定义指令详细攻略 Vue提供了许多内置指令用于操作DOM元素,如v-if、v-show、v-bind等。但是,如果我们想要自定义一些不同于Vue提供的指令来操作DOM元素,该怎么做呢?这时候,Vue的自定义指令就派上用场了。 自定义指令的基本使用 Vue允许开发者自定义指令,只需要在Vue实例中的directives选项中注册即可。 自定义指令需要定…

    Vue 2023年5月27日
    00
  • vue使用recorder.js实现录音功能

    下面是“Vue使用Recorder.js实现录音功能”的完整攻略: 1.引入Recorder.js 首先,在Vue项目中,需要引入Recorder.js。可以在项目中使用npm进行安装,也可以直接引入官方的Recorder.js文件: <script src="https://cdn.jsdelivr.net/gh/mattdiamond/R…

    Vue 2023年5月27日
    00
  • vue本地模拟服务器请求mock数据的方法详解

    Vue本地模拟服务器请求Mock数据的方法详解 在开发Vue项目的过程中,我们可能需要在本地预览和测试一些接口。但是在实际的开发中,如果后端接口还没有开发完毕,我们就无法进行测试了。这时候,模拟服务器请求Mock数据就显得尤为重要。本文将详细讲解Vue本地模拟服务器请求Mock数据的方法。 1. 创建Mock数据 首先需要创建Mock数据。在项目的src目录…

    Vue 2023年5月28日
    00
  • axios向后台传递数组作为参数的方法

    当使用 axios 向后台传递数组作为参数时,可以通过两种方法来实现。 方法一:使用 URLSearchParams 对象 在前端将数组转换为 URLSearchParams 对象,再通过 axios 发送请求。具体代码如下: import axios from ‘axios’; const params = new URLSearchParams(); c…

    Vue 2023年5月29日
    00
  • 一定要知道的 25 个 Vue 技巧

    一定要知道的 25 个 Vue 技巧攻略 Vue.js 是一个轻量级的 JavaScript 框架,其强大的数据绑定和组件化设计使得它成为了在前端开发中最热门的框架之一。在本文中,我将会向你介绍一些常用的 Vue 技巧,以帮助你更好的利用 Vue 的能力。 技巧 1:使用 v-cloak 防止 FOUC FOUC (Flash of Unstyled Con…

    Vue 2023年5月27日
    00
  • vue-quill-editor+plupload富文本编辑器实例详解

    Vue-Quill-Editor + Plupload 富文本编辑器实例攻略 1. 简介 在 Web 开发过程中,富文本编辑器是一个重要的工具,它可以让用户通过类似于微信公众号编辑器的方式撰写富文本内容,从而满足更多细节定制和更丰富的表现力需求。 Vue-Quill-Editor 是一款基于 Vue.js 的 Quill 富文本编辑器组件库,而 Pluplo…

    Vue 2023年5月28日
    00
合作推广
合作推广
分享本页
返回顶部