基于vue+element实现全局loading过程详解
项目中使用的是vue+element实现的全局loading
1.引入所需组件,这里主要就是router和element组件,element组件引入可以参考element官网
2.下面就是重点及代码实现了
首先是全局的一个变量配置参数,代码如下:
//全局页面跳转是否启用loading exportconstrouterLoading=true; //全局api接口调用是否启用loading exportconstapiLoading=true; //loading参数配置 exportconstloadingConfig={ lock:true, text:'Loading', spinner:'el-icon-loading', background:'rgba(0,0,0,0.7)' }
接下来是全局的一个loading简单封装,代码如下
importElementUIfrom'element-ui'; import{loadingConfig}from'../src/config/index'//全局的一个基本参数配置 varloading=null; constloadingShow=()=>{ loading=ElementUI.Loading.service(loadingConfig); } constloadingHide=()=>{ loading.close(); } constloadingObj={ loadingShow, loadingHide } exportdefaultloadingObj
页面跳转时全局配置loading,代码如下:
main.js中添加代码:
//TheVuebuildversiontoloadwiththe`import`command //(runtime-onlyorstandalone)hasbeensetinwebpack.base.confwithanalias. importVuefrom'vue' importAppfrom'./App' importrouterfrom'./router' importElementUIfrom'element-ui'; import'element-ui/lib/theme-chalk/index.css'; importglo_loadingfrom'../loading/index'//loading组件的简单封装 import{routerLoading}from'../src/config/index'//全局的页面跳转loading是否启用 Vue.use(ElementUI); Vue.config.productionTip=false /*eslint-disableno-new*/ newVue({ el:'#app', router, components:{App}, template:'' }) //从后台获取的用户角色 constrole='user' //当进入一个页面是会触发导航守卫router.beforeEach事件 router.beforeEach((to,from,next)=>{ routerLoading?glo_loading.loadingShow():''//如果全局启用页面跳转则加载loading if(to.meta.roles){ if(to.meta.roles.includes(role)){ next()//放行 }else{ next({path:"/404"})//跳到404页面 } }else{ next()//放行 } routerLoading?glo_loading.loadingHide():''//关闭loading层 })
在ajax请求的时候调用全局loading,代码如下:
//添加请求拦截器 service.interceptors.request.use(function(config){ //在发送请求之前做些什么 apiLoading?glo_loading.loadingShow():''//全局loading是否启用 returnconfig; },function(error){ //对请求错误做些什么 console.log(error); returnPromise.reject(error); }); //添加响应拦截器 service.interceptors.response.use(function(response){ //对响应数据做点什么 if(response.status==200){ returnresponse.data; }else{ Promise.reject(); } },function(error){ //对响应错误做点什么 console.log(error); apiLoading?glo_loading.loadingHide():'' returnPromise.reject(error); });
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。