vue项目全局配置loading(路由页面跳转和ajax请求)

项目中使用的是vue+element实现的全局loading

1.引入所需组件,这里主要就是router和element组件,element组件引入可以参考element官网

2.下面就是重点及代码实现了

首先是全局的一个变量配置参数,代码如下:

 1 //全局页面跳转是否启用loading
 2 export const routerLoading = true;
 3  
 4 //全局api接口调用是否启用loading
 5 export const apiLoading = true;
 6  
 7 //loading参数配置
 8 export const loadingConfig = {
 9   lock: true,
10   text: 'Loading',
11   spinner: 'el-icon-loading',
12   background: 'rgba(0, 0, 0, 0.7)'
13 }

接下来是全局的一个loading简单封装,代码如下

 1 import ElementUI from 'element-ui';
 2 import {loadingConfig} from '../src/config/index' //全局的一个基本参数配置
 3  
 4 var loading = null ;
 5 const loadingShow = () => {
 6   loading = ElementUI.Loading.service(loadingConfig);
 7 }
 8  
 9 const loadingHide = () => {
10   loading.close();
11 }
12  
13 const loadingObj={
14   loadingShow,
15   loadingHide
16 }
17  
18 export default loadingObj

页面跳转时全局配置loading,代码如下:

main.js中添加代码:

 1 // The Vue build version to load with the `import` command
 2 // (runtime-only or standalone) has been set in webpack.base.conf with an alias.
 3 import Vue from 'vue'
 4 import App from './App'
 5 import router from './router'
 6 import ElementUI from 'element-ui';
 7 import 'element-ui/lib/theme-chalk/index.css';
 8  
 9 import glo_loading from '../loading/index' //loading组件的简单封装
10 import {routerLoading} from '../src/config/index' //全局的页面跳转loading是否启用
11  
12 Vue.use(ElementUI);
13  
14 Vue.config.productionTip = false
15  
16 /* eslint-disable no-new */
17 new Vue({
18   el: '#app',
19   router,
20   components: { App },
21   template: '<App/>'
22 })
23  
24 //从后台获取的用户角色
25 const role = 'user'
26 //当进入一个页面是会触发导航守卫 router.beforeEach 事件
27 router.beforeEach((to,from,next) => {
28   routerLoading ? glo_loading.loadingShow() : '' //如果全局启用页面跳转则加载loading
29   if(to.meta.roles){
30     if(to.meta.roles.includes(role)){
31       next() //放行
32     }else{
33       next({path:"/404"}) //跳到404页面
34     }
35   }else{
36     next() //放行
37   }
38 routerLoading ? glo_loading.loadingHide() : ''//关闭loading层
39 })

在ajax请求的时候调用全局loading,代码如下:

 1 // 添加请求拦截器
 2 service.interceptors.request.use(function (config) {
 3   // 在发送请求之前做些什么
 4   apiLoading ? glo_loading.loadingShow() : ''//全局loading是否启用
 5   return config;
 6 }, function (error) {
 7   // 对请求错误做些什么
 8   console.log(error);
 9   return Promise.reject(error);
10 });
11  
12 // 添加响应拦截器
13 service.interceptors.response.use(function (response) {
14   // 对响应数据做点什么
15   if(response.status == 200){
16       return response.data;
17   }else{
18     Promise.reject();
19   }
20 }, function (error) {
21   // 对响应错误做点什么
22   console.log(error);
23   apiLoading ? glo_loading.loadingHide() : ''
24   return Promise.reject(error);
25 });
原文地址:https://www.cnblogs.com/yuwenjing0727/p/13272351.html