import router from './router' import store from './store' import NProgress from 'nprogress' // progress bar 进度条 import 'nprogress/nprogress.css' // progress bar style 进度条样式 import { Message } from 'element-ui' import { getToken } from '@/utils/auth' // getToken from cookie import Vue from 'vue' NProgress.configure({ showSpinner: false })// NProgress configuration const whiteList = ['/login', '/404', '/401'] // 不重定向白名单 // 全局钩子 router.beforeEach((to, from, next) => { console.log('toPath:' + to.path) NProgress.start() // 加载进度条 // 如果有token if (getToken()) { // 登录后进入登录页 if (to.path === '/login') { next({ path: '/' }) NProgress.done() // if current page is dashboard will not trigger afterEach hook, so manually handle it } else { // 当进入非登陆页时 if (store.getters.roleList.length === 0) { // 判断当前用户是否已拉取完user_info信息 store.dispatch('GetInfo').then(res => { // 拉取用户信息 // 设置当前子系统为基础资源子系统 const currentSys = { code: 'baseResourse', name: '基础资源子系统' } // 将当前系统信息保存在localStorage中 store.commit('SET_SYSTEM', currentSys) // 远程访问获取权限列表(菜单&按钮) store.dispatch('GetMenus', currentSys).then(() => { router.addRoutes(store.getters.addRouters) // 动态添加可访问路由表 next({ ...to, replace: true }) // hack方法 确保addRoutes已完成 ,set the replace: true so the navigation will not leave a history record }) }).catch((err) => { store.dispatch('FedLogOut').then(() => { Message.error(err || '权限验证失败,请重新登录系统') next({ path: '/' }) }) }) } else { next() } } } else { if (whiteList.indexOf(to.path) !== -1) { // 免登录白名单,直接进入 next() } else { // 获取链接里的token const token = to.query.token console.log('token' + to.query.token) if (token) { // 调用自动登录接口,否则跳转到登录页 store.dispatch('AppLogin', token).then(() => { console.log('自动登录成功') console.log(to.path) next({ ...to, replace: true }) // 登录成功继续 }).catch(() => { next('/401') // 否则全部重定向到401没有权限页面 }) } else { // 判断是独立运行的子系统还是和其他基础子系统一起的 const config = Vue.prototype.baseConfig if (config.singleSys) { next(`/login?redirect=${to.path}`) // 否则全部重定向到登录页 } else { window.location.href = config.mainPage } } NProgress.done() } } }) router.afterEach(() => { NProgress.done() // 结束Progress })