基于vue+element实现全局loading过程详解
项目中使用的是vue+element实现的全局loading
1.引入所需组件,这里主要就是router和element组件,element组件引入可以参考element官网
2.下面就是重点及代码实现了
首先是全局的一个变量配置参数,代码如下:
//全局页面跳转是否启用loadingexport const routerLoading = true;//全局api接口调用是否启用loadingexport const apiLoading = true;//loading参数配置export const loadingConfig = { lock: true, text: ’Loading’, spinner: ’el-icon-loading’, background: ’rgba(0, 0, 0, 0.7)’}
接下来是全局的一个loading简单封装,代码如下
import ElementUI from ’element-ui’;import {loadingConfig} from ’../src/config/index’ //全局的一个基本参数配置var loading = null ;const loadingShow = () => { loading = ElementUI.Loading.service(loadingConfig);}const loadingHide = () => { loading.close();}const loadingObj={ loadingShow, loadingHide}export default loadingObj
页面跳转时全局配置loading,代码如下:
main.js中添加代码:
// The Vue build version to load with the `import` command// (runtime-only or standalone) has been set in webpack.base.conf with an alias.import Vue from ’vue’import App from ’./App’import router from ’./router’import ElementUI from ’element-ui’;import ’element-ui/lib/theme-chalk/index.css’;import glo_loading from ’../loading/index’ //loading组件的简单封装import {routerLoading} from ’../src/config/index’ //全局的页面跳转loading是否启用Vue.use(ElementUI);Vue.config.productionTip = false/* eslint-disable no-new */new Vue({ el: ’#app’, router, components: { App }, template: ’<App/>’})//从后台获取的用户角色const role = ’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是否启用 return config;}, function (error) { // 对请求错误做些什么 console.log(error); return Promise.reject(error);});// 添加响应拦截器service.interceptors.response.use(function (response) { // 对响应数据做点什么 if(response.status == 200){ return response.data; }else{ Promise.reject(); }}, function (error) { // 对响应错误做点什么 console.log(error); apiLoading ? glo_loading.loadingHide() : ’’ return Promise.reject(error);});
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持好吧啦网。
相关文章:
1. 正则表达式匹配${key}并在Java中使用的详细方法2. python 解决pycharm运行py文件只有unittest选项的问题3. Python通过fnmatch模块实现文件名匹配4. Android Studio 4.0 正式发布在Ubuntu 20.04中安装的方法5. 解决vue scoped scss 无效的问题6. 低版本IE正常运行HTML5+CSS3网站的3种解决方案7. python+adb+monkey实现Rom稳定性测试详解8. 关于python中readlines函数的参数hint的相关知识总结9. 基于Java实现简单贪吃蛇游戏10. log4net在Asp.net MVC4中的使用过程
