1. Axios基础应用与核心原理
Axios作为现代前端开发中最流行的HTTP客户端之一,其简洁的API设计和强大的功能使其成为处理异步请求的首选工具。让我们从一个完整的Vue集成示例开始,逐步拆解其核心用法。
1.1 基础请求示例解析
下面是一个典型的Axios在Vue 3中的集成案例,展示了GET和POST两种基本请求方式:
html复制<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>AXIOSDemo</title>
</head>
<body>
<div id="app">
<input type="button" value="获取数据" @click="getEmployees">
<input type="button" value="提交数据" @click="addEmployee">
</div>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script type="module">
import { createApp } from 'https://unpkg.com/vue@3/dist/vue.esm-browser.js'
createApp({
data() {
return {
empList: []
}
},
methods: {
async getEmployees() {
await axios.get('http://localhost:8080/employees').then(res => {
this.empList = res.data;
console.log(this.empList);
}).catch(function(err) {
alert(err);
console.log(err);
return;
});
},
async addEmployee() {
await axios.post('http://localhost:8080/employees', {
name: 'mzj-2021',
email: 'mzj-2021@qq.com'
}).then(function(res) {
console.log(res.data);
alert("提交员工数据成功");
}).catch(function(err) {
alert(err);
console.log("提交员工数据失败",err);
return;
});
}
}
}).mount('#app');
</script>
</body>
</html>
这个示例中几个关键点值得注意:
- 通过CDN直接引入Axios,适合快速原型开发
- 使用Vue 3的Composition API风格
- 展示了Promise链式调用(.then/.catch)与async/await的混合用法
- 包含了完整的错误处理逻辑
1.2 请求配置最佳实践
实际项目中,我们通常会创建配置化的Axios实例:
javascript复制const apiClient = axios.create({
baseURL: 'http://localhost:8080',
timeout: 5000,
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer your_token_here'
}
});
// 使用实例
apiClient.get('/employees').then(...)
这种方式的优势包括:
- 统一的基础配置管理
- 避免重复代码
- 便于添加拦截器等全局功能
- 支持多API端点配置
需要模型API调用? 免费领10W Token,多模型网关一键接入 Claude、DeepSeek 等主流模型。
2. async/await的流程控制深度解析
理解async/await的执行流程是掌握现代JavaScript异步编程的关键。让我们通过实际场景深入分析其工作机制。
2.1 执行顺序的层次划分
javascript复制async function example() {
console.log('1. 外层开始'); // 同步代码
try {
console.log('2. try块开始'); // 同步代码
const res = await asyncOperation(); // 暂停点
console.log('3. 异步成功', res); // 微任务
} catch (err) {
console.log('4. 捕获错误', err); // 微任务
} finally {
console.log('5. 最终执行'); // 无论成功失败都执行
}
console.log('6. 外层结束'); // 同步代码(除非前面有return)
}
执行顺序说明:
- 外层同步代码立即执行(1、2)
- await暂停函数执行,将剩余代码包装为微任务
- 异步操作完成后,继续执行try块内后续代码(3)或跳转catch(4)
- finally块总是执行(5)
- 最后执行外层剩余同步代码(6),除非前面有return
2.2 实际应用中的分层策略
基于执行顺序特点,我们应该合理组织代码结构:
javascript复制async function getEmployees() {
// 外层:必执行的初始化工作
this.loading = true;
console.log('请求开始:', new Date());
try {
// 内层:核心业务逻辑
const res = await axios.get('/employees');
this.empList = this.transformData(res.data);
this.showSuccessToast('数据加载成功');
} catch (err) {
// 内层:错误处理
this.showErrorToast(err.message);
this.logErrorToService(er
