最近在研究动态添加路由菜单,菜单添加过滤什么都写好了,就在路由守卫拦截那一块出现了问题。动态路由数据存储在store内,用于判断是否刷新页面,后端拿取的菜单存在cookie内,这是我的代码:
添加路由的代码
export function addUserMenus() {
let menuList = getTrees(cookie.getJSON('menu'));
const addRoutes = [];
let tempList = [];
menuList.forEach(item1 => {
tempList = []
let parent = {
path: item1.url,
name: item1.comName,
component: () => import('@/views/system/' + item1.comName + '.vue')
}
let child = {
path: '',
name: '',
component: null
}
if (item1.children) {
item1.children.forEach(item2 => {
child.path = item2.url;
child.name = item2.comName;
child.component = () => import('@/views/system/' + item2.comName + '.vue');
tempList.push(child);
})
}
if (tempList.length > 0) {
addRoutes.push(Object.assign({}, parent, {
children: tempList
}))
} else {
addRoutes.push(parent);
}
})
addRoutes.forEach(item => {
router.addRoute('Home', item);
})
store.commit('setMenuRouter', addRoutes);
console.info("初始", router.getRoutes())
}
//全局路由拦截
router.beforeEach((to, from, next) => {
if (to.path == '/login') {
if (cookie.get('user') != null || cookie.get('menu') != null || cookie.get('token') != null) {
if (store.getters.getMenuRouter.length === 0) {
addUserMenus();
}
next("/home/info");
}
next();
} else {
if (cookie.get('user') == null || cookie.get('menu') == null || cookie.get('token') == null) {
cookie.remove('user');
cookie.remove('menu');
cookie.remove('token');
ElMessage.error("发生异常,请重新登录!");
next("/login");
} else {
if (store.getters.getMenuRouter.length === 0) {
addUserMenus();
}
next();
}
}
})
页面一刷新就跳到404,控制台打印显示我路由内有动态添加进去的路由,感觉是动态路由还没添加进静态路由内,就已经next() 放行了,也不太确定是不是这个问题,但是一点击404的返回就能正常浏览页面了,返回按钮是用router.push跳转的。