当前位置: 首页 > news >正文

Vue:axios(GET请求)

基础 GET 请求

axios.get('https://api.example.com/data').then(response => {console.log('响应数据:', response.data);}).catch(error => {console.error('请求失败:', error);});

参数传递方式

axios.get('/api/search', {params: {keyword: 'vue',page: 1,sort: 'desc'}
});// 实际请求 URL 变为:
// /api/search?keyword=vue&page=1&sort=desc

高级配置选项

axios.get('/api/data', {timeout: 5000, // 超时时间(毫秒)headers: {'X-Custom-Header': 'value','Authorization': 'Bearer ' + token},responseType: 'json', // 支持 arraybuffer/blob/document/json/textvalidateStatus: function (status) {return status >= 200 && status < 300; // 自定义成功状态码范围}
});

完整请求生命周期处理

// 显示加载状态
this.isLoading = true;axios.get('/api/products').then(response => {// 成功处理this.data = response.data;// 处理分页信息(假设后端返回如下结构)if(response.headers['x-total-count']) {this.total = parseInt(response.headers['x-total-count'], 10);}}).catch(error => {// 错误分类处理if (error.response) {// 服务器响应了非 2xx 状态码console.log('状态码:', error.response.status);console.log('响应头:', error.response.headers);} else if (error.request) {// 请求已发出但无响应console.error('无响应:', error.request);} else {// 请求配置错误console.error('配置错误:', error.message);}}).finally(() => {// 无论成功失败都执行this.isLoading = false;});

实用技巧

1. 请求取消
const source = axios.CancelToken.source();axios.get('/api/large-data', {cancelToken: source.token
});// 需要取消请求时(如组件销毁前)
source.cancel('用户主动取消请求');// 在 Vue 组件中使用
beforeDestroy() {this.source?.cancel();
}
2. 缓存处理
// 简单内存缓存实现
const cache = new Map();async function getWithCache(url) {if (cache.has(url)) {return cache.get(url);}const response = await axios.get(url);cache.set(url, response.data);return response.data;
}
3. 重试机制
function axiosGetWithRetry(url, retries = 3) {return new Promise((resolve, reject) => {const attempt = (remaining) => {axios.get(url).then(resolve).catch(error => {if (remaining > 0) {console.log(`剩余重试次数: ${remaining}`);attempt(remaining - 1);} else {reject(error);}});};attempt(retries);});
}

在 Vue 组件中的实践

export default {data() {return {posts: [],loading: false,error: null};},created() {this.loadPosts();},methods: {async loadPosts() {this.loading = true;this.error = null;try {const response = await axios.get('/api/posts', {params: {_limit: 10,_page: this.currentPage}});this.posts = response.data;} catch (err) {this.error = '加载失败: ' + err.message;} finally {this.loading = false;}}}
}
http://www.xdnf.cn/news/583219.html

相关文章:

  • 【VLNs篇】04:SayNav-为新环境中的动态规划到导航进行大型语言模型的基础构建
  • 批量处理合并拆分pdf功能 OCR 准确率高 免费开源
  • 华为昇腾开发——多模型资源管理(C++)
  • Apollo10.0学习——planning模块(9)之参数详解二
  • WooCommerce缓存教程 – 如何防止缓存破坏你的WooCommerce网站?
  • 7.2.顺序查找
  • 黑马点评前端Nginx启动失败问题解决记录
  • day26- 系统编程之 文件IO(II) 及 文件属性
  • 数据结构:绪论之时间复杂度与空间复杂度
  • 论文阅读笔记——PixArt-α,PixArt-δ
  • 滚珠导轨:重构精密仪器传动架构,开启微纳世界
  • C++-继承
  • k8s容器入门(1)有状态服务 vs 无状态服务 核心区别
  • list(c++)
  • 排序和排列——蓝桥杯备考
  • 在Java的list.forEach(即 Stream API 的 forEach 方法)中,无法直接使用 continue 或 break 语句的解决办法
  • Lucide:一款精美的开源矢量图标库,前端图标新选择
  • 5G 核心网中的 NPN 功能详解
  • MongoDB大数据量的优化——mongoTemplate.stream()方法使用
  • 参与开发的注意事项
  • 每日算法-250522
  • CUDA加速的线性代数求解器库cuSOLVER
  • Spring AI 之提示词
  • 智能IoT未来与边缘生态共建 | 2025 高通边缘智能创新应用大赛第六场公开课来袭!
  • go语言基础
  • FastAPI在 Nginx 和 Docker 环境中的部署
  • 【Python socket模块深度解析】网络通信的核心工具
  • 高性能图表库SciChart WPF v8.8全新发布——提升渐变颜色映射高度
  • Mysql的主从同步
  • VR溺水安全:为生命筑牢数字化防线