当前位置: 首页 > 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;}}}
}

相关文章:

  • leetcode 148. Sort List
  • ThreadLocal线程本地变量在dubbo服务使用时候遇到的一个坑
  • 深入剖析 5G 核心网中的 PLMN
  • Android 直播播放器FFmpeg静态库编译实战指南(NDK r21b)
  • 彩礼的异化:婚姻市场中的资本规训与性别政治批判
  • 什么是VR实景?有哪些高价值场景?
  • 5G基站选择±10ppm晶振及低相噪技术解析
  • MySQL中索引最左前缀法则、索引失效情况、前缀索引、索引设计原则
  • 技术分享 | MySQL大事务导致数据库卡顿
  • TensorFlow深度学习实战(17)——主成分分析详解
  • Python爬虫实战:研究Grab 框架相关技术
  • Linux系统编程 | IPC对象---消息队列
  • 同步/异步电路;同步/异步复位
  • 二叉树结构与遍历
  • 2025有铜半孔工艺参数设计规范
  • rt-linux下的底层锁依赖因cgroup cpu功能导致不相干进程的高时延问题
  • 引领“零碳会议”新风尚!第十届国际贸易发展论坛——绿色发展专场,在京举办
  • Linux探秘:驾驭开源,解锁高性能——基础指令(续集)
  • 【RocketMQ 生产者和消费者】- 生产者启动源码-创建 MQClientInstance(2)
  • 硬件,软件和进程
  • 网站后台登陆口/杭州网络
  • 手机微网站建设案例及报告/郑州网络推广专业公司
  • 东莞樟木头做网站哪家好/平台seo
  • 建设网站需要用到哪些软件/枣庄网站建设制作
  • 网站编辑工具/关键字优化用什么系统
  • 做网站买什么香港服务器/深圳做网站的公司有哪些