index.js 2.3 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
import router from './routers'
import store from '@/store'
import Config from '@/settings'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css'// progress bar style
import { getToken } from '@/utils/auth' // getToken from cookie
import { buildMenus } from '@/api/system/menu'
import { filterAsyncRouter } from '@/store/modules/permission'

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

const whiteList = ['/register', '/edge/Screen']	// no redirect whitelist

router.beforeEach((to, from, next) => {
	if (to.meta.title) {
		//document.title = to.meta.title + ' - ' + Config.title
		document.title = to.meta.title
	}
	NProgress.start();

	if (getToken()) {
		// 已登录且要跳转的页面是登录页
		if (to.path === '/plus/login') {
		  next({ path: '/' })
		  NProgress.done()
		} else {
		  if (store.getters.roles.length === 0) { // 判断当前用户是否已拉取完user_info信息
			store.dispatch('GetInfo').then(() => { // 拉取user_info
			  // 动态路由,拉取菜单
			  loadMenus(next, to)
			}).catch(() => {
			  store.dispatch('LogOut').then(() => {
				location.reload() // 为了重新实例化vue-router对象 避免bug
			  })
			})
		  // 登录时未拉取 菜单,在此处拉取
		  } else if (store.getters.loadMenus) {
			// 修改成false,防止死循环
			store.dispatch('updateLoadMenus')
			loadMenus(next, to)
		  } else {
			next()
		  }
		}
	} else {
		/* has no token*/
		if (whiteList.indexOf(to.path) !== -1) { // 在免登录白名单,直接进入
			next()
		} else {
			//window.location.href = `/plus/login?redirect=${to.fullPath}`;
			NProgress.done()
		}
	}
})

export const loadMenus = (next, to) => {
  buildMenus().then(res => {
    const sdata = JSON.parse(JSON.stringify(res))
    const rdata = JSON.parse(JSON.stringify(res))
    const sidebarRoutes = filterAsyncRouter(sdata)
    const rewriteRoutes = filterAsyncRouter(rdata, true)
    rewriteRoutes.push({ path: '*', redirect: '/404', hidden: true })
    store.dispatch('GenerateRoutes', rewriteRoutes).then(() => { // 存储路由
      router.addRoutes(rewriteRoutes) // 动态添加可访问路由表
      next({ ...to, replace: true })
    })
    store.dispatch('SetSidebarRouters', sidebarRoutes)
  })
}

router.afterEach(() => {
  NProgress.done() // finish progress bar
})