动态路由菜单
转载import router from './router';
import store from './store';
import NProgress from 'nprogress'; // progress bar
import 'nprogress/nprogress.css'; // progress bar style
import { getToken } from '@/utils/auth'; // get token from cookie
import getPageTitle from '@/utils/get-page-title';
import Layout from '@/layout';
const _import = require('./router/_import_' + process.env.NODE_ENV);
NProgress.configure({ showSpinner: false }); // NProgress Configuration
const whiteList = ['/login']; // no redirect whitelist
let getRouter;
router.beforeEach(async(to, from, next) => {
// start progress bar
NProgress.start();
// set page title
document.title = getPageTitle(to.meta.title);
// determine whether the user has logged in
const hasToken = getToken();
if (hasToken) {
// console.log('有token')
if (to.path === '/login') {
// if is logged in, redirect to the home page
next({ path: '/' });
NProgress.done();
} else {
if (getRouter) {
next();
} else {
const hasGetUserInfo = store.state.user.menus;
if (hasGetUserInfo) {
getRouter = store.getters.menus;
routerGo(to, next);// 执行路由跳转方法
} else {
try {
await store.dispatch('user/selectMenuBy', store.getters.name)
getRouter = store.getters.menus;
routerGo(to, next);// 执行路由跳转方法
} catch (error) {
await store.dispatch('user/resetToken');
// Message.error(error || 'Has Error')
next(`/login?redirect=${to.path}`);
NProgress.done();
}
}
}
}
} else {
/* has no token*/
if (whiteList.indexOf(to.path) !== -1) {
// in the free login whitelist, go directly
next();
} else {
// other pages that do not have permission to access are redirected to the login page.
next(`/login?redirect=${to.path}`);
NProgress.done();
}
}
});
router.afterEach(() => {
// finish progress bar
NProgress.done();
});
function filterAsyncRouter(asyncRouterMap) {
const accessedRouters = asyncRouterMap.filter(route => {
if (route.component) {
if (route.component === 'Layout') {
route.component = Layout;
} else {
route.component = _import(route.component);
}
}
if (route.children && route.children.length) {
route.children = filterAsyncRouter(route.children);
}
return true;
});
return accessedRouters;
}
function routerGo(to, next) {
getRouter = filterAsyncRouter(getRouter); // 过滤路由
router.addRoutes(getRouter); // 动态添加路由
global.antRouter = getRouter; // 将路由数据传递给全局变量,做侧边栏菜单渲染工作
next({ ...to, replace: true });
}
本文章为转载内容,我们尊重原作者对文章享有的著作权。如有内容错误或侵权问题,欢迎原作者联系我们进行内容更正或删除文章。
提问和评论都可以,用心的回复会被更多人看到
评论
发布评论
相关文章
-
Vue路由:动态路由(参数)
Vue Router 是 Vue.js 官方的路由管理器,用于在单页应用(SPA)中进行页面的路由跳转与状态管理。它可以帮助你在一个应用中实现不
vue.js javascript 前端 前端框架 Vue -
ios h5往里面增加元素会跳一下
###1.Html5 Forms概述,在Html5中: 1.表单仍然使用<form>元素作为容器,我们可以在其中设置基本的提交特性 form的act
ios h5往里面增加元素会跳一下 表单 控件 输入框