項目中使用的是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 });