axios请求拦截器实现数据加载出来之前loading效果
步骤:先用css做一个loading动画,默认为隐藏,在请求拦截器时让动画显示,在响应拦截器中让动画隐藏
首先我们在template中写html
<template>
<div id="app">
<div id="content">
<div class="box" v-show="flag">
<div class="loader">
<div class="loading-3">
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
</div>
</div>
</div>
<router-view/>
</div>
</div>
</template>
然后在css中写样式
.box {
width: 100%;
padding: 3%;
box-sizing: border-box;
overflow: hidden;
margin-left: 110px;
margin-top: 150px;
}
.box .loader {
width: 30%;
float: left;
height: 200px;
margin-right: 3%;
box-sizing: border-box;
display: flex;
align-items: center;
justify-content: center
}
@-webkit-keyframes loading-3 {
50% {
transform: scale(.4);
opacity: .3
}
100% {
transform: scale(1);
opacity: 1
}
}
.loading-3 {
position: relative
}
.loading-3 span {
display: block;
width: 15px;
height: 15px;
border-radius: 50%;
background-color: #333;
position: absolute
}
.loading-3 span:nth-of-type(1) {
top: 25px;
left: 0;
-webkit-animation: loading-3 1s ease 0s infinite
}
.loading-3 span:nth-of-type(2) {
top: 17px;
left: 17px;
-webkit-animation: loading-3 1s ease -.12s infinite
}
.loading-3 span:nth-of-type(3) {
top: 0;
left: 25px;
-webkit-animation: loading-3 1s ease -.24s infinite
}
.loading-3 span:nth-of-type(4) {
top: -17px;
left: 17px;
-webkit-animation: loading-3 1s ease -.36s infinite
}
.loading-3 span:nth-of-type(5) {
top: -25px;
left: 0;
-webkit-animation: loading-3 1s ease -.48s infinite
}
.loading-3 span:nth-of-type(6) {
top: -17px;
left: -17px;
-webkit-animation: loading-3 1s ease -.6s infinite
}
.loading-3 span:nth-of-type(7) {
top: 0;
left: -25px;
-webkit-animation: loading-3 1s ease -.72s infinite
}
.loading-3 span:nth-of-type(8) {
top: 17px;
left: -17px;
-webkit-animation: loading-3 1s ease -.84s infinite
}
然后在created钩子函数中写拦截器
created(){
axios.interceptors.request.use((config)=>{
// 在发送请求之前做些什么
this.flag = true
//请求时让loading动画显示
return config;
}, function (error) {
// 对请求错误做些什么
return Promise.reject(error);
});
// 添加响应拦截器
axios.interceptors.response.use((response)=> {
// 对响应数据做点什么
this.flag = false
//让loading动画隐藏
return response;
}, function (error) {
// 对响应错误做点什么
return Promise.reject(error);
});
}
小结:总的来说就是使用请求拦截器和响应拦截器在控制loading动画的显示隐藏,想在哪使用就在相应的组件中编写即可,我需要的是全局的所以是在app.vue中写的