import router from './index.js';
|
import NProgress from 'nprogress';
|
import 'nprogress/nprogress.css';
|
import {auth} from '@/plugins';
|
import {isHttp} from '@/utils/validate';
|
import {useUserStore, useSettingStore, useMenuStore} from '@/store/modules';
|
|
NProgress.configure({showSpinner: false});
|
|
const whiteList = ['/login'];
|
|
router.beforeEach(async (to, from, next) => {
|
NProgress.start();
|
/**
|
* 在免登录白名单,直接进入
|
*/
|
if (whiteList.indexOf(to.path) !== -1) {
|
next();
|
return;
|
}
|
|
const token = auth.getToken();
|
|
/**
|
* 否则全部重定向到登录页
|
*/
|
if (!token) {
|
next(`/login?redirect=${to.fullPath}`) // 否则全部重定向到登录页
|
NProgress.done();
|
return;
|
}
|
|
if (token) {
|
/**
|
* 动态修改标题
|
*/
|
to.meta.title && useSettingStore().setTitle(to.meta.title);
|
|
if (to.path === '/login' || to.path === '/') {
|
next({path: '/index'});
|
NProgress.done();
|
return;
|
}
|
|
if (useUserStore().user === null) {
|
const [accessRoutes] = await Promise.all(
|
[
|
useMenuStore().getMenu(),
|
useUserStore().getUser()
|
]
|
);
|
accessRoutes.forEach(route => {
|
if (!isHttp(route.path)) {
|
/**
|
* 动态添加可访问路由表
|
*/
|
router.addRoute(route);
|
}
|
});
|
/**
|
* hack方法 确保addRoutes已完成
|
*/
|
next({...to, replace: true});
|
return;
|
}
|
|
next();
|
}
|
})
|
|
router.afterEach(() => {
|
NProgress.done()
|
})
|