基础 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'
}
});
高级配置选项
axios.get('/api/data', {
timeout: 5000,
headers: {
'X-Custom-Header': 'value',
'Authorization': 'Bearer ' + token
},
responseType: 'json',
validateStatus: 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) {
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('用户主动取消请求');
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;
}
}
}
}