前言
每个项目在做网络请求的时候,没有loading是一件很尴尬的事情。用户点了之后没有得到及时的反馈,有种假死的感觉,所以需要一个loading提示用户正在加载。
实现方式
当然是用CSS3的animation写,这样占用资源最少,执行效率最高。 本次的loading是通用写法
码上就来
以React实现为例
css
-
把边框变圆,然后消去任意一边的边框的颜色。造成圆缺的感觉
-
用一层绝对布局的全屏透明的div把loading的包裹,使得loading覆盖全屏。
-
在全屏的div中使用flex布局,使得loading全屏居中
.loadingWrap {
height: 100vh;
width: 100vw;
display: flex;
justify-content: center;
align-items: center;
.loading {
width: 80px;
height: 80px;
border: 10px solid #333333;
border-bottom: #cccccc 10px solid;
border-radius: 50%;
-webkit-animation: load 1.1s infinite linear;
}
}
@-webkit-keyframes load {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}
js
- 现代前端框架是不建议我们直接操作DOM的
- 当时loading、toast这种全局组件,直接操作DOM才是最高效的做法。因为无需经常修改组件状态
- 生产DOM把loading挂上去,然后设置div为绝对布局
let container: any
export const Loading = () => {
return (
<div className={style.loadingWrap}>
<div className={style.loading}></div>
</div>
)
}
export const showLoading = () => {
container = window.document.getElementById('app_loading')
if (!container) {
container = window.document.createElement('div')
container.setAttribute('style', 'position: absolute;top:0;')
container.id = 'app_loading'
window.document.body.appendChild(container)
} else {
container.setAttribute('style', 'position: absolute;top:0;')
}
ReactDOM.render(<Loading />, container)
}
export const hiddenLoading = () => {
container = window.document.getElementById('app_loading')
if (container) {
container.setAttribute('style', 'position: absolute;top:0;display:none;')
}
}
使用
- 在网络请求中拦截request,使用showLoading()
- 在网络请求中拦截request,使用hiddenLoading()