vue 全局请求加载自定义动画
时间: 2023-09-27 21:12:09 浏览: 165
在 Vue 中,可以通过在 axios 的拦截器中添加一个 loading 动画,来实现全局请求加载自定义动画的效果。以下是一个简单的示例代码:
1. 先在你的项目中安装 axios 和 loading 动画库,比如 vue-spinners。
```bash
npm install axios vue-spinners --save
```
2. 在 main.js 中引入 axios 和 vue-spinners,并添加 axios 的拦截器。
```javascript
import axios from 'axios'
import Vue from 'vue'
import { PulseLoader } from 'vue-spinners'
Vue.component('pulse-loader', PulseLoader)
axios.interceptors.request.use(config => {
// 显示 loading 动画
Vue.prototype.$loading.show({
container: null,
color: '#3eaf7c',
size: '50px',
backgroundColor: 'transparent',
zIndex: 99999,
isFullPage: true,
type: 'pulse'
})
return config
}, error => {
return Promise.reject(error)
})
axios.interceptors.response.use(response => {
// 隐藏 loading 动画
Vue.prototype.$loading.hide()
return response
}, error => {
// 隐藏 loading 动画
Vue.prototype.$loading.hide()
return Promise.reject(error)
})
Vue.prototype.$http = axios
```
3. 在需要发送请求的组件中使用 `$http` 来发送请求。
```javascript
this.$http.get('/api/data').then(response => {
console.log(response.data)
}).catch(error => {
console.log(error)
})
```
这样就可以在全局请求发送时显示 loading 动画了。如果你想自定义 loading 动画,可以根据自己的需求修改上面的代码。
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.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)
![.zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)