Vue 3 + Axios 完整入门实战指南

从入门到深入,手把手教你在 Vue 3 中正确使用 Axios,支持全局挂载、局部分离、使用 proxy 连接场景,适合所有前端小白和实战设计。

大家好,我是石小石!一个热爱技术分享的开源社区贡献者,小册《油猴脚本实战指南》作者、CSDN专栏《Vite极速入门通关教程》作者。


一、安装 Axios

js 复制代码
npm install axios

二、Vue 3 中将 Axios 全局挂载

Vue 3 不再支持 Vue 2 中的 Vue.prototype 方式,而是通过 app.config.globalProperties 来达到相同效果:

全局挂载

js 复制代码
// main.js
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import axios from 'axios'

const app = createApp(App)
app.config.globalProperties.$http = axios

app.use(router).mount("#app")

三、在组件中使用 Axios

使用 getCurrentInstance 获取当前实例 (dev-only)

js 复制代码
import { getCurrentInstance, onMounted } from 'vue'

export default {
  setup() {
    const { ctx } = getCurrentInstance();
    onMounted(() => {
      ctx.$http.get('/api/user').then(res => console.log(res));
    });
  }
};

使用 proxy 替代 ctx (推荐)

js 复制代码
import { getCurrentInstance, onMounted } from 'vue'

export default {
  setup() {
    const { proxy } = getCurrentInstance();
    onMounted(() => {
      proxy.$http.get('/api/user').then(res => console.log(res));
    });
  }
};

应对环境错误:ctx 在打包后无法访问 globalProperties,需要使用 proxy 替代。


四、局部引入 + 分类使用

创建 /proxy/index.js

js 复制代码
// proxy/index.js
import axios from 'axios';

const getList = (url) => axios.get(url);

export default {
  getList
};

在组件中使用

js 复制代码
import axiosProxy from '../proxy';

axiosProxy.getList('/api/todoList/list').then(res => {
  console.log(res.data);
});

五、Axios 基础用法

GET 请求

js 复制代码
axios.get('/user?id=12345')
  .then(res => console.log(res))
  .catch(err => console.error(err));

POST 请求

js 复制代码
axios.post('/user', {
  firstName: 'Fred',
  lastName: 'Flintstone'
}).then(res => console.log(res));

六、通用 config 配置

js 复制代码
axios({
  method: 'post',
  url: '/user',
  data: {
    firstName: 'Fred'
  },
  timeout: 1000,
  headers: {
    'X-Requested-With': 'XMLHttpRequest'
  }
});

常用 config 项目概览

项目 说明
url 请求地址
method 方法 (get/post)
baseURL 基础路径
headers 请求头
params url 取值参数
data 请求体数据 (post 用)
timeout 超时时间

七、定义全局默认配置

js 复制代码
axios.defaults.baseURL = 'https://api.example.com';
axios.defaults.headers.common['Authorization'] = 'Bearer token';
axios.defaults.timeout = 5000;

八、自定义实例 + 拦截器

定义一个独立实例

js 复制代码
const instance = axios.create({
  baseURL: '/api',
  timeout: 10000,
});

拦截器

js 复制代码
instance.interceptors.request.use(config => {
  // 添加公共 token
  config.headers.Authorization = 'Bearer your_token';
  return config;
}, error => Promise.reject(error));

instance.interceptors.response.use(response => {
  return response.data; // 简化接口结果
}, error => Promise.reject(error));

九、返回结构

Axios 的响应包括如下结构:

js 复制代码
{
  data: {},         // 接口返回数据
  status: 200,     // HTTP 状态码
  statusText: 'OK',
  headers: {},
  config: {},      // 当前配置
  request: {}      // XMLHttpRequest 对象
}

实际使用

js 复制代码
axios.get('/user/12345').then(res => {
  console.log(res.data);
});

十、推荐扩展

  • 把 axios 包装成 hooks
  • 封装连接失败提示 / 热更新负载
  • 通过 provide/inject 分类控制 API 请求成本

总结

Vue 3 + Axios 是最常用的前后端通讯配置,重点是「全局 globalProperties 挂载 + proxy 替代 this + 分类 request」,这是一套无需完全依赖 UI 框架的经典组合技术路线,非常适合工程化开发和小组件开发。

关于我

最近在学习油猴脚本开发,写了很多有趣的脚本:

  • 接口拦截工具:修改CSDN博客数据接口返回值
  • Vue路由一键切换:开发效率起飞
  • 任意元素双击实现画中画:摸鱼超级助手
  • 掘金后台自动签到助手
  • 解除文本复制、网页复制、一键下载为MD
  • 主题切换助手

如果你对油猴脚本开发也感兴趣,可以参考我的油猴脚本开发教程

相关推荐
崔庆才丨静觅16 分钟前
hCaptcha 验证码图像识别 API 对接教程
前端
passerby60611 小时前
完成前端时间处理的另一块版图
前端·github·web components
掘了1 小时前
「2025 年终总结」在所有失去的人中,我最怀念我自己
前端·后端·年终总结
崔庆才丨静觅1 小时前
实用免费的 Short URL 短链接 API 对接说明
前端
崔庆才丨静觅2 小时前
5分钟快速搭建 AI 平台并用它赚钱!
前端
崔庆才丨静觅2 小时前
比官方便宜一半以上!Midjourney API 申请及使用
前端
Moment2 小时前
富文本编辑器在 AI 时代为什么这么受欢迎
前端·javascript·后端
崔庆才丨静觅2 小时前
刷屏全网的“nano-banana”API接入指南!0.1元/张量产高清创意图,开发者必藏
前端
剪刀石头布啊2 小时前
jwt介绍
前端
爱敲代码的小鱼2 小时前
AJAX(异步交互的技术来实现从服务端中获取数据):
前端·javascript·ajax