当前位置:首页 > VUE

vue实现axio请求

2026-01-17 04:57:19VUE

安装 Axios

在 Vue 项目中安装 Axios,可以通过 npm 或 yarn 进行安装。打开终端并运行以下命令:

npm install axios

yarn add axios

引入 Axios

在需要使用 Axios 的组件或文件中,引入 Axios:

import axios from 'axios';

发起 GET 请求

使用 Axios 发起 GET 请求获取数据:

vue实现axio请求

axios.get('https://api.example.com/data')
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    console.error(error);
  });

发起 POST 请求

使用 Axios 发起 POST 请求发送数据:

axios.post('https://api.example.com/data', { key: 'value' })
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    console.error(error);
  });

全局配置 Axios

可以在项目的入口文件(如 main.js)中配置 Axios 的全局默认值:

axios.defaults.baseURL = 'https://api.example.com';
axios.defaults.headers.common['Authorization'] = 'Bearer token';

封装 Axios 实例

为了更好地管理请求,可以封装一个 Axios 实例:

vue实现axio请求

const api = axios.create({
  baseURL: 'https://api.example.com',
  timeout: 1000,
  headers: { 'X-Custom-Header': 'foobar' }
});

api.get('/data')
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    console.error(error);
  });

拦截请求和响应

可以使用拦截器在请求或响应被处理前做一些操作:

axios.interceptors.request.use(
  config => {
    console.log('Request sent');
    return config;
  },
  error => {
    return Promise.reject(error);
  }
);

axios.interceptors.response.use(
  response => {
    console.log('Response received');
    return response;
  },
  error => {
    return Promise.reject(error);
  }
);

处理并发请求

使用 axios.allaxios.spread 处理多个并发请求:

axios.all([
  axios.get('https://api.example.com/data1'),
  axios.get('https://api.example.com/data2')
])
.then(axios.spread((response1, response2) => {
  console.log(response1.data, response2.data);
}))
.catch(error => {
  console.error(error);
});

取消请求

可以使用 CancelToken 取消请求:

const CancelToken = axios.CancelToken;
const source = CancelToken.source();

axios.get('https://api.example.com/data', {
  cancelToken: source.token
})
.then(response => {
  console.log(response.data);
})
.catch(error => {
  if (axios.isCancel(error)) {
    console.log('Request canceled', error.message);
  } else {
    console.error(error);
  }
});

source.cancel('Operation canceled by the user.');

标签: vueaxio
分享给朋友:

相关文章

vue实现矩阵

vue实现矩阵

Vue 实现矩阵的方法 在 Vue 中实现矩阵操作可以通过多种方式完成,以下是一些常见的方法: 使用二维数组表示矩阵 矩阵可以用二维数组来表示,每个元素对应矩阵中的一个值。在 Vue 的 data…

vue实现公告

vue实现公告

Vue 实现公告功能的方法 公告功能通常需要实现滚动展示、自动切换或固定显示的效果。以下是几种常见的实现方式: 使用 marquee 标签实现滚动公告 <template> &l…

vue 实现href

vue 实现href

Vue 实现 href 的方法 在 Vue 中实现 href 功能可以通过多种方式,具体取决于需求场景。以下是几种常见的方法: 使用 <a> 标签 直接使用 HTML 的 <a&g…

vue实现弹幕

vue实现弹幕

Vue 实现弹幕功能 弹幕功能通常包括动态生成、滚动显示、颜色和速度随机化等特性。以下是基于 Vue 3 的实现方法。 核心思路 使用 CSS 动画控制弹幕从右向左滚动。 动态生成弹幕数据,随机设置…

vue 实现搜索

vue 实现搜索

实现 Vue 搜索功能 在 Vue 中实现搜索功能通常涉及以下几个关键步骤: 数据绑定与输入监听 使用 v-model 双向绑定搜索输入框的值,监听用户输入: <template>…

vue实现gps

vue实现gps

Vue 中实现 GPS 定位功能 在 Vue 中实现 GPS 定位功能通常依赖于浏览器的 Geolocation API 或第三方地图服务(如高德、百度地图等)。以下是两种常见的实现方式: 使用浏览…