vue中axios的二次封装
时间: 2023-11-04 22:56:02 浏览: 43
在Vue项目中,我们通常使用Axios作为网络请求的库。但是,在实际开发中,我们往往需要对Axios进行二次封装,以方便我们的使用和维护。以下是一个简单的Axios二次封装的示例:
1. 创建一个axios.js文件,用于封装Axios:
```javascript
import axios from 'axios';
const instance = axios.create({
baseURL: 'https://your.api.com', // 接口基础路径
timeout: 10000, // 请求超时时间
headers: {} // 请求头
});
// 请求拦截器
instance.interceptors.request.use(
config => {
// 在请求发送之前做些什么
const token = localStorage.getItem('token');
if (token) {
config.headers.Authorization = token;
}
return config;
},
error => {
// 对请求错误做些什么
return Promise.reject(error);
}
);
// 响应拦截器
instance.interceptors.response.use(
response => {
// 对响应数据做些什么
return response.data;
},
error => {
// 对响应错误做些什么
return Promise.reject(error);
}
);
export default instance;
```
2. 创建一个api.js文件,用于封装API请求:
```javascript
import axios from './axios';
// 封装API请求
export const get = (url, params) => {
return axios.get(url, { params });
};
export const post = (url, data) => {
return axios.post(url, data);
};
export const put = (url, data) => {
return axios.put(url, data);
};
export const del = (url, data) => {
return axios.delete(url, { data });
};
```
3. 在Vue组件中使用封装好的API请求:
```javascript
import { get, post } from '@/api';
export default {
data() {
return {
list: []
};
},
methods: {
fetchData() {
get('/api/list').then(res => {
this.list = res;
});
},
submitData() {
post('/api/add', { name: 'Tom', age: 18 }).then(res => {
console.log(res);
});
}
}
};
```
通过以上的封装,我们可以方便地使用Axios进行API请求,并且可以方便地维护请求和响应拦截器,以及统一设置请求头和超时时间等参数。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)