You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
|
|
import router from './routers' import store from '@/store' import Config from '@/settings' // 导入进度条
import NProgress from 'nprogress' import 'nprogress/nprogress.css' import { getToken } from '@/utils/auth' import { filterAsyncRouter } from '@/store/modules/permission' import { buildMenus } from '@/api/system/menu'
NProgress.configure({ showSpinner: false })
// 重新定向白名单
const whiteList = ['/login']
// 路由守卫,路由跳转前执行钩子函数
// to:目标路由对象
// from:当前路由
// next:放行或重载
router.beforeEach((to, from, next) => { // 如果路由标题设置则显示配置标题和目标菜单标题
if (to.meta.title) { document.title = to.meta.title + '-' + Config.title } // 加载效果
NProgress.start() // 如果已登录过且要跳转的页面是登录页,执行下一次路由守卫
if (getToken()) { if (to.path === '/login') { next({ path: '/' }) NProgress.done() } else { // 保存在store 中路由不为空则放行,判断用户是否拉取用户信息
if (store.getters.roles.length === 0) { // 拉取user_info
store.dispatch('GetInfo').then(() => { // 加载动态路由,拉取菜单
loadMenus(next, to) }) .catch(() => { store.dispatch('LogOut').then(() => { // 重新实例化路由对象 避免bug
location.reload() }) }) // 登录时未拉取菜单,在此拉取
} else if (store.getters.loadMenus) { // 防止死循环
store.dispatch('updateLoadMenus') loadMenus(next, to) } else { next() } } } else { // hsa no token
// 在免登录白名单,直接进入
if (whiteList.indexOf(to.path) !== -1) { next() } else { // 否则全部重定向到登录页面
next(`/login?redirect=${to.fullPath}`) // next()
NProgress.done() } } 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(() => { /* * 在addRoutes()之后第一次访问被添加的路由会白屏, * 这是因为刚刚addRoutes()就立刻访问被添加的路由, * 然而此时addRoutes()没有执行结束, * 因而找不到刚刚被添加的路由导致白屏 */ router.addRoutes(rewriteRoutes) /* * 确保addRoutes()时动态添加的路由已经被完全加载上去 * replace: true只是一个设置信息, * 告诉VUE本次操作后, * 不能通过浏览器后退按钮,返回前一个路由 */ next({ ...to, replace: true }) }) store.dispatch('SetSidebarRouters', sidebarRoutes) }) } // 进度条
router.afterEach(() => { NProgress.done() })
|