import router from './router' import store from './store' import { Message } from 'element-ui' import NProgress from 'nprogress' // progress bar import 'nprogress/nprogress.css' // progress bar style import { getToken } from '@/static/utils/auth' // get token from cookie import getPageTitle from '@/static/utils/get-page-title' NProgress.configure({ showSpinner: false }) // NProgress Configuration const whiteList = ['/login', '/bizLogin','/lifeLine','/door','/deviceh5','/assitsdanger', '/ssoLogin'] // no redirect whitelist 路由白名单 router.beforeEach(async(to, from, next) => { //console.log('beforeEach') // console.log('to', to) // console.log('from', from) // console.log('next', next) // start progress bar NProgress.start() // set page title document.title = getPageTitle(to.meta.title) // //console.log('title', document.title) // 先判断白名单放行,在判断token问题 // if (whiteList.indexOf(to.path) !== -1) { // 先判断白名单放行,支持正则判断 @modify by xiecf if (whiteList.some(whiteItem => typeof whiteItem === 'string' ? to.path === whiteItem : whiteItem.test(to.path))) { // in the free login whitelist, go directly next() NProgress.done() return } // determine whether the user has logged in const hasToken = getToken() // //console.log('token', hasToken) if (hasToken) { //console.log('to.path', to.path) if (to.path === '/login') { // if is logged in, redirect to the home page next({ path: '/' }) // //console.log('toLogin') NProgress.done() } else { const hasGetUserInfo = store.getters.name // //console.log('hasGetUserInfo', hasGetUserInfo) if (hasGetUserInfo) { next() } else { try { store .dispatch('user/getUserInfo') .then(res => { // 拉取user_info const perms = res.perms // note: perms must be a array! such as: ['GET /aaa','POST /bbb'] // //console.log('perms', perms) if (perms) { store .dispatch('GenerateRoutes', perms) .then(() => { // 根据perms权限生成可访问的路由表 // //console.log('_addRouters', store.getters.addRouters) 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 => { //console.log( // err + 'store.dispatchuser/getUserInfo 报错' // ) }) } catch (error) { // remove token and go to login page to re-login //console.log('_loginError') await store.dispatch('user/resetToken') Message.error(error || 'Has Error') next(`/login`) NProgress.done() } } } } else { /* has no token*/ // //console.log('whiteList', whiteList, to.path) next(`/login`) NProgress.done() } }) router.afterEach(() => { //console.log('afterEach') // finish progress bar NProgress.done() })