岳飞的弟弟,镜辟天,寻找失散的洪门兄弟
实现全局loading加载
分析需求,我们只需要在请求发起的时候开始loading,响应结束的时候关闭loading,就这么简单 对不对?
import axios from 'axios'; import { message, loading } from 'element-ui'; import cookies from 'js-cookie'; import router from '@/router/index' let loading //定义loading变量 function startloading() { //使用element loading-start 方法 loading = loading.service({ lock: true, text: '加载中……', background: 'rgba(0, 0, 0, 0.7)' }) } function endloading() { //使用element loading-close 方法 loading.close() } //那么 showfullscreenloading() tryhidefullscreenloading() 要干的事儿就是将同一时刻的请求合并。 //声明一个变量 needloadingrequestcount,每次调用showfullscreenloading方法 needloadingrequestcount + 1。 //调用tryhidefullscreenloading()方法,needloadingrequestcount - 1。needloadingrequestcount为 0 时,结束 loading。 let needloadingrequestcount = 0 export function showfullscreenloading() { if (needloadingrequestcount === 0) { startloading() } needloadingrequestcount++ } export function tryhidefullscreenloading() { if (needloadingrequestcount <= 0) return needloadingrequestcount-- if (needloadingrequestcount === 0) { endloading() } } //http request 拦截器 axios.interceptors.request.use( config => { var token = '' if(typeof cookies.get('user') === 'undefined'){ //此时为空 }else { token = json.parse(cookies.get('user')).token }//注意使用的时候需要引入cookie方法,推荐js-cookie 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); } ); //http response 拦截器 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) } )
以上这篇vue+axios+element ui 实现全局loading加载示例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持移动技术网。
如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复
VUE+elementui组件在table-cell单元格中绘制微型echarts图
Vue通过getAction的finally来最大程度避免影响主数据呈现问题
vue 路由懒加载中给 Webpack Chunks 命名的方法
网友评论