在 router.beforeEach 钩子中,即跳转页面前——获取后端返回的用户信息、存起来,用于加载侧边栏、配置路由等。
1 router.js 文件
引入 router
全局使用 router
创建 router 实例
输出 router 实例
2 main.js
3 router.js 中 菜单配置
在 router.beforeEach 中配置总菜单(常用菜单+后端返回的菜单)
子菜单需要用到递归!!
// 生成嵌套路由(子路由)functiongenerateChildRouters(data){const routers=[];for(var itemof data){if(item.menuType==2){continue;}try{let component="";if(!item.component)continue;if(item.component.indexOf("layouts")>=0){
component="views/other/"+ item.component;}else{
component="views/"+ item.component;}// eslint-disable-next-lineletURL=(item.meta.url||'').replace(/{{([^}}]+)?}}/g,(s1, s2)=>eval(s2))// URL支持{{ window.xxx }}占位符变量if(isURL(URL)){
item.meta.url=URL;}let menu={
path: item.path,
name: item.name,
redirect: item.redirect,
component:()=>import(`@/${component}.vue`),
hidden: item.hidden,//component:()=> import(`@/views/${item.component}.vue`),
meta:{
title: item.meta.title,
icon: item.meta.icon,
url: item.meta.url,
permissionList: item.permissionList}}if(item.alwaysShow){
menu.alwaysShow=true;}if(item.children&& item.children.length>0){
menu.children=[...generateChildRouters(item.children)];}//--update-begin----author:scott---date:20190320------for:根据后台菜单配置,判断是否路由菜单字段,动态选择是否生成路由(为了支持参数URL菜单)------//判断是否生成路由if(item.route&& item.route==='0'){//console.log(' 不生成路由 item.route: '+item.route);//console.log(' 不生成路由 item.path: '+item.path);}else{
routers.push(menu);}}catch(e){
console.log(item);
console.log("子路由加载个别出错!", e)}//--update-end----author:scott---date:20190320------for:根据后台菜单配置,判断是否路由菜单字段,动态选择是否生成路由(为了支持参数URL菜单)------}return routers}
最后所有路由都加载到了router上了
菜单加载