Vue:axios(GET请求)

基础 GET 请求

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

参数传递方式

javascript 复制代码
axios.get('/api/search', {
  params: {
    keyword: 'vue',
    page: 1,
    sort: 'desc'
  }
});

// 实际请求 URL 变为:
// /api/search?keyword=vue&page=1&sort=desc

高级配置选项

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

完整请求生命周期处理

javascript 复制代码
// 显示加载状态
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. 请求取消
javascript 复制代码
const source = axios.CancelToken.source();

axios.get('/api/large-data', {
  cancelToken: source.token
});

// 需要取消请求时(如组件销毁前)
source.cancel('用户主动取消请求');

// 在 Vue 组件中使用
beforeDestroy() {
  this.source?.cancel();
}
2. 缓存处理
javascript 复制代码
// 简单内存缓存实现
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. 重试机制
javascript 复制代码
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 组件中的实践

javascript 复制代码
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;
      }
    }
  }
}
相关推荐
大明者省2 小时前
AI 在课程思政的 10 大应用:从资源挖掘到效果升华
前端·人工智能·easyui
饺子大魔王的男人6 小时前
【Three.js】机器人管线包模拟
javascript·机器人
知否技术6 小时前
知道这10个npm工具包,开发效率提高好几倍!第2个大家都用过!
前端·npm
希希不嘻嘻~傻希希7 小时前
CSS 字体与文本样式笔记
开发语言·前端·javascript·css·ecmascript
石小石Orz7 小时前
分享10个吊炸天的油猴脚本,2025最新!
前端
爷_8 小时前
Nest.js 最佳实践:异步上下文(Context)实现自动填充
前端·javascript·后端
爱上妖精的尾巴8 小时前
3-19 WPS JS宏调用工作表函数(JS 宏与工作表函数双剑合壁)学习笔记
服务器·前端·javascript·wps·js宏·jsa
草履虫建模8 小时前
Web开发全栈流程 - Spring boot +Vue 前后端分离
java·前端·vue.js·spring boot·阿里云·elementui·mybatis
—Qeyser8 小时前
让 Deepseek 写电器电费计算器(html版本)
前端·javascript·css·html·deepseek
UI设计和前端开发从业者9 小时前
从UI前端到数字孪生:构建数据驱动的智能生态系统
前端·ui