vue实现axio请求
Vue 中使用 Axios 发起 HTTP 请求
Axios 是一个基于 Promise 的 HTTP 客户端,适用于浏览器和 Node.js。在 Vue 项目中,可以通过以下方式集成并使用 Axios。
安装 Axios
通过 npm 或 yarn 安装 Axios:
npm install axios
# 或
yarn add axios
全局配置 Axios
在 Vue 项目的入口文件(如 main.js)中全局引入 Axios,并配置默认选项:
import axios from 'axios';
// 设置默认 baseURL
axios.defaults.baseURL = 'https://api.example.com';
// 请求拦截器
axios.interceptors.request.use(config => {
// 在发送请求前添加 token 等操作
config.headers.Authorization = `Bearer ${localStorage.getItem('token')}`;
return config;
}, error => {
return Promise.reject(error);
});
// 响应拦截器
axios.interceptors.response.use(response => {
// 对响应数据预处理
return response.data;
}, error => {
// 统一处理错误
return Promise.reject(error);
});
// 挂载到 Vue 原型链
Vue.prototype.$http = axios;
发起请求示例
在 Vue 组件中直接调用 Axios 发起请求:
GET 请求
this.$http.get('/users')
.then(response => {
console.log(response);
})
.catch(error => {
console.error(error);
});
POST 请求
this.$http.post('/users', { name: 'John', age: 30 })
.then(response => {
console.log(response);
})
.catch(error => {
console.error(error);
});
并发请求
使用 axios.all 和 axios.spread 处理多个并发请求:
axios.all([
this.$http.get('/users/1'),
this.$http.get('/users/2')
]).then(axios.spread((user1, user2) => {
console.log(user1, user2);
}));
封装为独立模块
可以将 Axios 封装为独立的服务模块,便于统一管理 API:
创建 api.js
import axios from 'axios';
const api = axios.create({
baseURL: 'https://api.example.com',
timeout: 5000
});
export default {
getUsers() {
return api.get('/users');
},
createUser(data) {
return api.post('/users', data);
}
};
在组件中使用
import api from '@/services/api';
export default {
methods: {
fetchUsers() {
api.getUsers()
.then(response => {
console.log(response);
});
}
}
};
注意事项
-
使用
async/await简化异步代码:async fetchData() { try { const response = await this.$http.get('/users'); console.log(response); } catch (error) { console.error(error); } } -
取消请求:
const source = axios.CancelToken.source(); this.$http.get('/users', { cancelToken: source.token }) .then(response => { /* ... */ }) .catch(thrown => { if (axios.isCancel(thrown)) { console.log('Request canceled:', thrown.message); } }); // 取消请求 source.cancel('Operation canceled by user.');
通过以上方法,可以在 Vue 项目中高效地使用 Axios 处理 HTTP 请求。







