Newer
Older
newBaseFront / src / permission.js
StephanieGitHub on 12 Aug 2021 1 KB MOD: vue-cli2代码迁移
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

NProgress.configure({ showSpinner: false })// NProgress configuration

const whiteList = ['/login', 'config/baseconfig'] // 不重定向白名单
// 全局钩子
router.beforeEach(async(to, from, next) => {
  NProgress.start() // 加载进度条
  // 如果有token
  const hasToken = getToken()
  if (hasToken) {
    // 登录后进入登录页
    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信息
        try {
          await store.dispatch('GetInfo')
          const accessRoutes = await store.dispatch('GetMenus')
          router.addRoutes(accessRoutes)
          next({ ...to, replace: true }) // hack方法 确保addRoutes已完成 ,set the replace: true so the navigation will not leave a history record
        } catch (err) {
          await store.dispatch('FedLogOut')
          Message.error(err || '权限验证失败,请重新登录系统')
          next({ path: '/' })
        }
      } else {
        next()
      }
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) { // 免登录白名单,直接进入
      next()
    } else {
      next(`/login?redirect=${to.path}`) // 否则全部重定向到登录页
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  NProgress.done() // 结束Progress
})