permission.js 2.58 KB
import router from './router'
import store from './vuex/store'
import NProgress from 'nprogress' // Progress 进度条
import 'nprogress/nprogress.css' // Progress 进度条样式
import { Message } from 'element-ui'
import { asynRouter } from './router'

let firstPath = '/'
const whiteList = ['/login', '/', '/404','/privacy','/active/location'] // 不重定向白名单
NProgress.configure({
  showSpinner: false,
})

router.beforeEach((to, from, next) => {
  NProgress.start()
  //const hasToken = getToken()
  document.title = '虎哥e盾|' + to.meta.title
  const hasToken = sessionStorage.getItem('token')
  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 {
      let hasMenu =
        store.state.common.permission &&
        store.state.common.permission.length > 0
      if (hasMenu) {
        next()
      } else {
        console.log('进入此处')
        try {
          store.dispatch('getRoleInfo').then((data) => {
            // if (data && data.permission) {
            //   const allPath = getPathArr(data.permission)
            //   const fullPathRoutes = getFullPath(asynRouter)
            //   const allRoutes = filterRoutes(fullPathRoutes, allPath)

            //   const menuItems = getMenuItems(filterMenuItems([...allRoutes]))
            //   firstPath = getFirstPath(allRoutes)

            //   store.dispatch('setPermission', menuItems)
            //   //store.dispatch('SET_MENU', menuItems)
            //   router.addRoutes(allRoutes)
            // }
            next({ ...to, replace: true })

            // if (to.path === '/' && to.matched.length === 0) {
            //   next({
            //     ...to,
            //     path: firstPath,
            //   })
            //   return
            // }

            if (store.getters.zlAccount && to.path === '/') {
              next({ path: '/monitor/monitor' })
              return
            }
            //next({ ...to })
          })
        } catch {
          //store.dispatch('user/resetToken')
          Message.error(error || 'Has Error')
          next(`/login?redirect=${to.path}`)
          NProgress.done()
        }
      }
    }
  } else {
    //console.log(to.path);
    //console.log(whiteList.indexOf(to.path) !== -1);
    //return false;
    if (whiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      next(`/`) // 否则全部重定向到登录页
      NProgress.done()
    }
  }
})

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