当前位置:首页 > VUE

vue实现axio请求

2026-03-09 09:59:08VUE

安装 Axios

在 Vue 项目中安装 Axios,可以通过 npm 或 yarn 进行安装:

npm install axios
# 或
yarn add axios

全局引入 Axios

main.jsmain.ts 中全局引入 Axios,并挂载到 Vue 实例上:

import Vue from 'vue'
import axios from 'axios'

Vue.prototype.$axios = axios

发起 GET 请求

在 Vue 组件中发起 GET 请求:

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

发起 POST 请求

在 Vue 组件中发起 POST 请求:

this.$axios.post('/api/data', { key: 'value' })
  .then(response => {
    console.log(response.data)
  })
  .catch(error => {
    console.error(error)
  })

配置请求拦截器

在全局配置请求拦截器,用于添加请求头或处理请求数据:

axios.interceptors.request.use(config => {
  config.headers.Authorization = 'Bearer token'
  return config
}, error => {
  return Promise.reject(error)
})

配置响应拦截器

在全局配置响应拦截器,用于统一处理响应数据或错误:

axios.interceptors.response.use(response => {
  return response.data
}, error => {
  return Promise.reject(error)
})

封装 Axios 实例

封装一个自定义的 Axios 实例,便于统一管理请求配置:

const instance = axios.create({
  baseURL: 'https://api.example.com',
  timeout: 5000
})

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

使用 async/await

在 Vue 组件中使用 async/await 处理异步请求:

vue实现axio请求

async fetchData() {
  try {
    const response = await this.$axios.get('/api/data')
    console.log(response.data)
  } catch (error) {
    console.error(error)
  }
}

标签: vueaxio
分享给朋友:

相关文章

vue实现文档

vue实现文档

Vue 实现文档的方法 在 Vue 中实现文档功能可以通过多种方式,包括使用富文本编辑器、Markdown 解析或直接渲染 HTML。以下是几种常见的实现方法。 使用富文本编辑器 富文本编辑器如 T…

vue实现单据

vue实现单据

Vue 实现单据功能的方法 使用 Vue 实现单据功能通常涉及表单设计、数据绑定、验证和提交等环节。以下是具体实现方案: 表单设计与数据绑定 使用 Vue 的 v-model 指令实现表单数据的双向…

vue实现vnc

vue实现vnc

Vue 实现 VNC 客户端 在 Vue 项目中实现 VNC 客户端功能,可以通过集成现有的 VNC 客户端库或组件完成。以下是具体实现方法: 安装依赖库 使用 noVNC 或其他 VNC 客户端…

vue实现flvvideo

vue实现flvvideo

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

vue 实现评分

vue 实现评分

Vue 实现评分功能 在 Vue 中实现评分功能可以通过多种方式完成,包括使用第三方组件库或自定义实现。以下是两种常见的方法: 使用第三方组件库(如 Element UI) Element UI 提…

vue实现hovuer

vue实现hovuer

Vue 实现 Hover 效果 在 Vue 中实现 hover 效果可以通过多种方式完成,以下是几种常见的方法: 使用 CSS 直接控制 通过 :hover 伪类实现,无需额外的 JavaScrip…