你想在 Vue3 里实现 AJAX 异步请求(接口调用、获取/提交数据),我会给你最常用、最简单的两种方案,直接复制就能用。
一、首选方案:axios(最推荐)
Vue3 官方不再内置 AJAX 库,axios 是行业标准,用法简单、稳定。
1. 安装 axios
在项目根目录执行:
npm install axios
# 或
yarn add axios
2. 在 Vue3 组件中使用(组合式 API)
<template>
<div>
<h2>请求数据</h2>
<button @click="getData">点击获取数据</button>
<div v-if="loading">加载中...</div>
<div v-else-if="error">{{ error }}</div>
<div v-else>{{ data }}</div>
</div>
</template>
<script setup>
// 1. 引入 axios
import axios from 'axios'
// 2. 引入响应式API
import { ref } from 'vue'
// 定义响应式数据
const data = ref(null)
const loading = ref(false)
const error = ref('')
// 3. 封装请求方法
const getData = async () => {
loading.value = true
error.value = ''
try {
// 发送 GET 请求(替换成你的接口地址)
const res = await axios.get('https://jsonplaceholder.typicode.com/todos/1')
data.value = res.data
} catch (err) {
error.value = '请求失败:' + err.message
} finally {
loading.value = false
}
}
</script>
3. 常用请求方式
// GET 请求(带参数)
axios.get('/api/list', {
params: { id: 1, name: 'test' }
})
// POST 请求(提交数据)
axios.post('/api/add', {
username: '张三',
age: 20
})
二、原生方案:fetch(无需安装)
浏览器原生自带,不用装任何依赖,适合简单场景。
<script setup>
import { ref } from 'vue'
const data = ref(null)
const getData = async () => {
try {
const res = await fetch('https://jsonplaceholder.typicode.com/todos/1')
const result = await res.json()
data.value = result
} catch (err) {
console.error('请求失败', err)
}
}
</script>
三、全局配置 axios(项目必备)
在 main.js 中统一配置基础路径、请求头:
import { createApp } from 'vue'
import App from './App.vue'
import axios from 'axios'
const app = createApp(App)
// 配置基础URL
axios.defaults.baseURL = 'http://localhost:3000'
// 全局挂载,组件中直接用 $axios
app.config.globalProperties.$axios = axios
app.mount('#app')
组件里直接用:
const res = await this.$axios.get('/api/list')
四、快速选择建议
- 项目开发 → 用 axios(功能全、好处理异常、支持拦截器)
- 简单demo/不想装依赖 → 用 fetch
总结
- Vue3 推荐 axios 做 AJAX,先安装再使用
- 用
async/await写异步代码最简洁 - 记得处理
loading和error提升用户体验 - 全局配置
baseURL方便统一管理接口