You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue.js 中如何发起 HTTP 请求?

Vue.js 执行HTTP请求的常用方案

Vue 本身未内置官方封装的HTTP客户端模块,和Angular自带@angular/common/http的设计不同,你可以通过以下几种常用方案实现HTTP请求:

1. 浏览器原生Fetch API

适合轻量项目、不需要复杂请求配置的场景,无需额外安装任何依赖,所有现代浏览器均原生支持:

  • 基础GET请求示例:
fetch('https://api.example.com/data')
  .then(response => response.json())
  .then(data => console.log('请求结果:', data))
  .catch(error => console.error('请求出错:', error))
  • 带提交数据的POST请求示例:
fetch('https://api.example.com/submit', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    name: '测试用户',
    id: 123
  })
})
.then(res => res.json())
.then(data => console.log(data))

2. 第三方库Axios

Axios是目前Vue生态中使用最广泛的HTTP请求方案,支持请求/响应拦截、自动转换JSON数据、客户端XSRF防护、兼容低版本浏览器等特性,能满足绝大多数业务场景的需求:

  • 安装命令:npm install axios
  • 基础用法示例:
// 引入axios
import axios from 'axios'

// 带查询参数的GET请求
axios.get('https://api.example.com/list', {
  params: {
    page: 1,
    pageSize: 10
  }
})
.then(res => {
  // 接口返回数据存于res.data中
  console.log(res.data)
})
.catch(err => console.error(err))

// POST提交JSON数据
axios.post('https://api.example.com/add', {
  title: '新内容',
  status: 1
})
.then(res => console.log(res.data))

如果需要全局调用,可在项目入口文件中挂载到Vue全局实例:

// Vue 2 写法
Vue.prototype.$http = axios

// Vue 3 写法
app.config.globalProperties.$http = axios

// 组件内直接调用
this.$http.get('/api/data').then(res => {})

3. 上层框架内置请求能力

如果你使用的是Nuxt这类Vue生态的全栈/元框架,框架本身会内置封装好的请求方法,比如Nuxt的useFetch、$fetch,天然支持服务端渲染同构请求,无需额外引入第三方库即可直接使用。

内容的提问来源于stack exchange,提问作者Adelin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.16 20:06:06