随笔 - 748  文章 - 1  评论 - 107  阅读 - 34万

【转】[Vue] Axios 的用法

转自:kimi.ai

在 Vue.js 中,axios 是一个非常流行的 HTTP 客户端库,用于发送 HTTP 请求(如 GET、POST、PUT、DELETE 等)。它支持浏览器和 Node.js 环境,并且具有简洁的 API 和强大的功能。以下是 axios 在 Vue 中的常见用法。

1. 安装 Axios

在项目中使用 axios,首先需要安装它。可以通过 npm 或 yarn 来安装:
bash复制
npm install axios
或者
bash复制
yarn add axios

2. 在 Vue 中使用 Axios

2.1 基本用法

在 Vue 组件中,可以通过 import 引入 axios,然后使用它发送请求。
JavaScript复制
<template>
  <div>
    <h1>User Data</h1>
    <ul>
      <li v-for="user in users" :key="user.id">{{ user.name }}</li>
    </ul>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      users: []
    };
  },
  created() {
    axios.get('https://jsonplaceholder.typicode.com/users')
      .then(response => {
        this.users = response.data;
      })
      .catch(error => {
        console.error('There was an error fetching the users:', error);
      });
  }
};
</script>

说明:

  • 使用 axios.get 发送 GET 请求。
  • 请求的 URL 是 https://jsonplaceholder.typicode.com/users,这是一个公共的测试 API。
  • .then() 中处理响应数据,将返回的用户数据赋值给 users
  • .catch() 中捕获可能发生的错误。

2.2 发送 POST 请求

如果需要发送 POST 请求,可以使用 axios.post 方法。例如,向服务器提交表单数据:
JavaScript复制
<template>
  <div>
    <form @submit.prevent="submitForm">
      <input v-model="formData.name" placeholder="Name">
      <input v-model="formData.email" placeholder="Email">
      <button type="submit">Submit</button>
    </form>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      formData: {
        name: '',
        email: ''
      }
    };
  },
  methods: {
    submitForm() {
      axios.post('https://jsonplaceholder.typicode.com/posts', this.formData)
        .then(response => {
          alert('Form submitted successfully!');
          console.log(response.data);
        })
        .catch(error => {
          console.error('There was an error submitting the form:', error);
        });
    }
  }
};
</script>

说明:

  • 使用 axios.post 发送 POST 请求。
  • 第一个参数是请求的 URL,第二个参数是要提交的数据(this.formData)。
  • .then() 中处理响应,例如弹出提示框。
  • .catch() 中捕获错误。

3. 配置 Axios

3.1 全局配置

可以通过 axios.defaults 设置全局配置,例如默认的请求 URL、超时时间等:
JavaScript复制
import axios from 'axios';

// 设置默认的请求 URL
axios.defaults.baseURL = 'https://jsonplaceholder.typicode.com';

// 设置超时时间
axios.defaults.timeout = 5000;

// 设置请求头
axios.defaults.headers.common['Authorization'] = 'Bearer your-token';

3.2 创建 Axios 实例

如果需要为不同的请求配置不同的设置,可以创建 Axios 实例:
JavaScript复制
import axios from 'axios';

const customAxios = axios.create({
  baseURL: 'https://jsonplaceholder.typicode.com',
  timeout: 5000,
  headers: { 'Authorization': 'Bearer your-token' }
});

export default customAxios;
然后在组件中使用这个实例:
JavaScript复制
import customAxios from './customAxios';

export default {
  created() {
    customAxios.get('/users')
      .then(response => {
        console.log(response.data);
      })
      .catch(error => {
        console.error(error);
      });
  }
};

4. 拦截器

axios 提供了拦截器功能,可以拦截请求和响应,进行统一处理。例如,添加请求拦截器和响应拦截器:
JavaScript复制
import axios from 'axios';

// 请求拦截器
axios.interceptors.request.use(config => {
  console.log('Request Interceptor:', config);
  // 可以在这里修改请求配置
  return config;
}, error => {
  console.error('Request Error:', error);
  return Promise.reject(error);
});

// 响应拦截器
axios.interceptors.response.use(response => {
  console.log('Response Interceptor:', response);
  // 可以在这里处理响应数据
  return response;
}, error => {
  console.error('Response Error:', error);
  return Promise.reject(error);
});

5. 错误处理

在使用 axios 时,错误处理非常重要。可以通过 .catch() 捕获错误,并根据错误类型进行处理:
JavaScript复制
axios.get('/users')
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    if (error.response) {
      // 请求已发出,但服务器响应的状态码不在 2xx 范围内
      console.error('Response Error:', error.response.status);
    } else if (error.request) {
      // 请求已发出,但没有收到响应
      console.error('Request Error:', error.request);
    } else {
      // 在设置请求时发生了一些事情,触发了一个错误
      console.error('Error:', error.message);
    }
  });

6. 使用 Vue-Axios 插件

Vue 官方提供了一个插件 vue-axios,可以将 axios 作为 Vue 的全局实例,方便在组件中直接使用。

安装

bash复制
npm install vue-axios

使用

JavaScript复制
import Vue from 'vue';
import axios from 'axios';
import VueAxios from 'vue-axios';

Vue.use(VueAxios, axios);

export default {
  created() {
    this.$axios.get('/users')
      .then(response => {
        console.log(response.data);
      })
      .catch(error => {
        console.error(error);
      });
  }
};
通过这种方式,可以在组件中直接使用 this.$axios 来发送请求。

总结

axios 是一个功能强大且易于使用的 HTTP 客户端库,适用于 Vue.js 项目。通过合理配置和使用拦截器、实例化等特性,可以更好地管理 HTTP 请求和响应,提高代码的可维护性和复用性。
posted on   z5337  阅读(43)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示