在vue2中我们通常使用如下方式添加动态路由:
router.addRoute(parentOrRoute, route) //添加单个\
router.addRoutes(routes) //添加多个
在vue3中的动态添加路由只保留了addRoute这一个方法,
下面看具体代码:
动态添加com:
function formatModules(_modules: any, result: any[]) {
// eslint-disable-next-line
Array.isArray(_modules) &&
_modules.forEach((menu: any) => {
const com = getComponent(menu.meta.locale);
const isCom = menu.meta.locale.split('.').length;
let component: any;
if (isCom === 1) {
component = DEFAULT_LAYOUT;
} else if (isCom === 2) {
component = PAGE_LAYOUT;
} else {
component = com;
}
const temp = {
path: menu.path,
name: menu.name,
meta: menu.meta,
component,
children: <any>[],
};
if (menu.children) {
temp.children = formatModules(menu.children, []);
}
result.push(temp);
});
return result;
}
getCom方法:单独的map.js
const dashboard = () => import('@/views/dashboard/index.vue');
// eslint-disable-next-line no-console
// 遍历菜单模块 建议:按照菜单大类区分,并带上注释
const mapping: any = {
// 首页
'dashboard.dashboard.dashboard': dashboard, // 首页
};
export const getComponent = (code: string) => {
return mapping[code];
};
通过api获取菜单list,并且动态注册路由:
async getMenuData(router: any) {
//router:any 此为默认路由方法,我是通过函数传递的
// 登录成功后刷路由接口,获取路由信息
this.menuList = [
{
path: '/after',
name: '按钮',
meta: {
locale: 'after',
icon: 'icon-dashboard',
},
children: [
{
path: 'afterInfo',
name: '按钮权限',
meta: {
locale: 'after.afterInfo',
},
children: [
{
path: '/after/afterInfo/afterList', // 全路径
name: '按钮权限实例',
meta: {
title: '按钮权限实例', // 必须
locale: 'after.afterInfo.afterList',
requiresAuth: true,
isTag: true,
parentPath: '/after', // 必须 必须要和一级path一致
permission: ['admin', 'add'], // 必须 按钮权限
},
},
],
},
],
},
];
this.appRoutes = await formatModules(this.menuList, []);
if (this.appRoutes.length > 0) {
// eslint-disable-next-line
for (const item of this.appRoutes) {
router.addRoute(item);
}
}
},