在項目中常常會有在請求先後加loading或者加加載進度條,通常這些組件都會抽離出來做爲全局組件react
進度條的插件貌似都不是很符合本身項目中的需求,因而。。ios
參考nprogress樣式,本身在項目中封裝組件,實現簡單的頂部加載進度條。效果以下web
組件放到components文件夾下,新建progress文件夾axios
progress/index.jsxapp
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import ReactDOM from 'react-dom'; import './progress.less' let defaultState = {show:false} class Progress extends Component { constructor(props, context){ super(props, context) this.state = {...defaultState} } start(){ // 開始顯示 this.setState({ show:true }) } done(){ // 結束隱藏 this.setState({ show:false }) } render(){ return ( <div className="myprogress" style={this.state.show? {display:'block'}:{display:'none'}}> <div className="bar"> <div className="peg"></div> </div> <div className="spinner"> <div className="spinner-icon"></div> </div> </div> ) } }
// 建立元素追加到body let div = document.createElement('div'); let props = { }; document.body.appendChild(div); let Box = ReactDOM.render(React.createElement( Progress, props ),div); export default Box;
progress/progress.lessless
@themecolor:#ffc900; .myprogress { pointer-events: none; .bar {background: @themecolor;position: fixed;z-index: 1031;top: 0; left: 0;width: 100%;height: 2px;} .peg {display: block;position: absolute;right: 0px;width: 100px;height: 100%;box-shadow: 0 0 10px @themecolor, 0 0 5px @themecolor; opacity: 1.0;-webkit-transform: rotate(3deg) translate(0px, -4px); -ms-transform: rotate(3deg) translate(0px, -4px);transform: rotate(3deg) translate(0px, -4px);} .spinner {display: block;position: fixed;z-index: 1031;top: 15px;right: 15px;} .spinner-icon {width: 18px;height: 18px;box-sizing: border-box; border: solid 2px transparent;border-top-color: @themecolor;border-left-color: @themecolor;border-radius: 50%; -webkit-animation: myprogress-spinner 400ms linear infinite; animation: myprogress-spinner 400ms linear infinite;} .myprogress-custom-parent {overflow: hidden;position: relative;} } .myprogress-custom-parent .myprogress .spinner, .myprogress-custom-parent .myprogress .bar { position: absolute; } @-webkit-keyframes myprogress-spinner { 0% { -webkit-transform: rotate(0deg); } 100% { -webkit-transform: rotate(360deg); } } @keyframes myprogress-spinner { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }
使用--(在請求攔截器里加,請求開始以前加,請求結束隱藏)dom
import axios from 'axios' import MProgress from '@/components/progress' // 設置超時時間 axios.defaults.timeout = 10000 axios.interceptors.request.use(config=>{ // 請求以前加loading MProgress.start(); return config },error=>{ return Promise.reject(error) }) axios.interceptors.response.use(config=>{ // 響應成功關閉loading MProgress.done(); return config },error=>{ return Promise.reject(error) }) export default axios;
以上,封裝遮罩層、彈出層同理this