当前位置:首页 > 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 请求获取数据:

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 实例:

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 取消请求:

vue实现axio请求

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实现rtc

vue实现rtc

Vue 实现 RTC 的步骤 安装依赖 在 Vue 项目中安装 WebRTC 相关依赖,如 simple-peer 或 peerjs,用于简化 WebRTC 的实现。 运行以下命令安装 simple-…

vue实现换行

vue实现换行

Vue 中实现换行的几种方法 在 Vue 中实现换行可以通过多种方式,具体取决于使用场景和需求。以下是常见的几种方法: 使用 HTML 的 <br> 标签 在模板中直接使用 <br…

vue实现路由

vue实现路由

Vue 路由的实现方法 Vue 路由可以通过 Vue Router 库来实现,Vue Router 是 Vue.js 官方的路由管理器,用于构建单页面应用(SPA)。 安装 Vue Router 通…

vue 实现全屏

vue 实现全屏

Vue 实现全屏功能 在 Vue 中实现全屏功能可以通过浏览器提供的 Fullscreen API 完成。以下是一个完整的实现方案: 安装依赖(可选) 如果需要跨浏览器兼容性更好,可以安装 scre…

vue实现flvvideo

vue实现flvvideo

vue-flv-player 实现 FLV 视频播放 安装依赖包 npm install flv.js vue-flv-player 基础组件引入 <template> <v…

vue实现datalist

vue实现datalist

使用 Vue 实现 HTML5 的 datalist 功能 HTML5 的 <datalist> 元素提供了一种自动完成输入框的功能,允许用户在输入时从预定义的选项列表中选择。以下是几种在…