vue响应拦截公共提示
时间: 2023-05-31 15:06:21 浏览: 132
在Vue应用中,我们可以利用axios的拦截器机制对所有的http请求和响应进行拦截和处理。在响应拦截中,我们可以统一处理服务器返回的错误信息,并且在页面中展示出来,以方便用户查看和操作。
以下是一个简单的示例代码,展示了如何在vue中实现响应拦截公共提示:
```javascript
import axios from 'axios';
import { Message } from 'element-ui';
// 创建axios实例
const service = axios.create({
baseURL: process.env.BASE_API,
timeout: 5000 // 请求超时时间
});
// 响应拦截器
service.interceptors.response.use(
response => {
const res = response.data;
if (res.code !== 200) { // 处理服务器返回的错误信息
Message({
message: res.message || 'Error',
type: 'error',
duration: 5 * 1000
});
return Promise.reject(new Error(res.message || 'Error'));
} else {
return res;
}
},
error => {
console.log('err' + error); // for debug
Message({
message: error.message,
type: 'error',
duration: 5 * 1000
});
return Promise.reject(error);
}
);
export default service;
```
在上面的代码中,我们使用了element-ui提供的Message组件来展示错误提示,你可以根据项目实际情况选择合适的方式来展示提示信息。
最后,我们将包装好的axios实例导出,方便在项目中使用。例如:
```javascript
import request from '@/utils/request';
export function login(data) {
return request({
url: '/user/login',
method: 'post',
data
});
}
```
阅读全文
相关推荐
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)