VUE3 动态添加路由
在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);
}
}
},
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通