在我们的平时的开发中,在前后端交互的时候,为了提高页面的观赏性和用户的体验,我们会在页面上添加loading来阻止用户操作来等待接口的返回,这个时候我们会考虑到全局loading还是局部loading,下面一起共享。
实现全局loading加载,首先分析需求,我们只需要在请求发起的时候开始loading,响应结束的时候关闭loading,简单逻辑而达到封装。
用到的插件:
1、element-ui–>ui库
2、lodash—>高效的JavaScript库
3、axios—>基于promise的http库
实现效果:
实现代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
| import axios from 'axios';
import { Message, Loading } from 'element-ui';
import Cookies from 'js-cookie';
import router from '@/router/index'
let loading
function startLoading() { loading = Loading.service({ lock: true, text: '加载中……', background: 'rgba(0, 0, 0, 0.7)' }) } function endLoading() { loading.close() }
let needLoadingRequestCount = 0 export function showFullScreenLoading() { if (needLoadingRequestCount === 0) { startLoading() } needLoadingRequestCount++ }
export function tryHideFullScreenLoading() { if (needLoadingRequestCount <= 0) return needLoadingRequestCount-- if (needLoadingRequestCount === 0) { endLoading() } }
axios.interceptors.request.use( config => { var token = '' if(typeof Cookies.get('user') === 'undefined'){ }else { token = JSON.parse(Cookies.get('user')).token } config.data = JSON.stringify(config.data); config.headers = { 'Content-Type':'application/json' } if(token != ''){ config.headers.token = token; } showFullScreenLoading() return config; }, error => { return Promise.reject(err); } );
axios.interceptors.response.use( response => { if(response.data.code == 'W_100004' || response.data.message == '用户未登录或登录超时,请登录!'){ router.push({ path:"/", querry:{redirect:router.currentRoute.fullPath} }) } tryHideFullScreenLoading() return response; }, error => { return Promise.reject(error) } )
|