前面讲了Vue2项目中动态添加路由及生成菜单,今天尝试在Vue3中动态添加路由及生成菜单。vue
最近在尝试用Vue3开发个管理平台项目,一切都是从头开始,基本框架搭建,熟悉Vue3写法,编写登陆页,编写路由守卫,上面功能已基本完成,开始编写首页布局,用Vue3就必须用Router4.x版本,因此以前的代码迁移过来以后发现,动态路由不生效,查了不少资料,最后发现,Router4中,去掉了 router.addRoutes ,只能使用 addRoute git
因此以前的写法就要相应的调整,以前是能够动态添加更多的路由规则,参数必须是一个符合 routes 选项要求的数组。数组
router.addRoutes(routes: Array<RouteConfig>);
如今是只能添加一个架构
router.addRoute("名称", { path: `/index`, name: '首页', component: () => import(`@/index.vue`) });
接下来就详细说明框架
1 路由数据封装ide
前台把路由写在代码里,这种方式只适用部分状况,因此大部分状况是路由后台提供,好比返回格式以下:布局
{ "code": 0, "msg": "success", "data": [{ "id": 1000, "parentId": -1, "icon": "iconquanxian", "name": "组织架构", "path": "/system", "component": "Layout", "redirect": null, "type": "0", "children": [{ "id": 1100, "parentId": 1000, "children": [], "icon": "iconyonghuguanli", "name": "用户管理", "path": "/user", "component": "views/system/user/index", "redirect": null, "type": "0", }], }, { "id": 2000, "parentId": -1, "icon": "iconquanxian", "name": "权限管理", "path": "/organization", "component": "Layout", "redirect": null, "type": "0", "children": [{ "id": 2100, "parentId": 2000, "children": [], "icon": "iconyonghuguanli", "name": "菜单管理", "path": "/menu", "component": "views/system/user/index", "redirect": null, "type": "0", }], }] }
这种是后台树型结构返回,前台不须要进行二次处理能够直接显示成菜单,spa
<a-menu theme="dark" mode="inline" > <a-sub-menu v-for="subitem in menuData.menu" :key="subitem.path"> <template #title> <Icon-font :type="subitem.icon" /> <span>{{ subitem.name }}</span> </template> <a-menu-item v-for="item in subitem.children" :key="item.path">{{ item.name }}</a-menu-item> </a-sub-menu> </a-menu>
可是路由须要从新封装,先说说用到的字段,path-路由地址、component这个如今有两种,一种是Layout表明父菜单,另外一种views开头的是组件地址。那么咱们就能够开始动态生成路由了,写法和Vue2项目有所不一样,首先定义一个方法,code
const routerPackag = routers => { routers.filter(itemRouter => { if (itemRouter.component != "Layout") { router.addRoute("BasicLayout", { path: `${itemRouter.path}`, name: itemRouter.name, component: () => import(`@/${itemRouter.component}`) }); } // 是否存在子集 if (itemRouter.children && itemRouter.children.length) { routerPackag(itemRouter.children); } return true; }); };
2 调用component
上面这个方式是动态生成路由,接下来就是调用这个方法。
getBasisMenu().then(res => { if (res.code == 0) { routerPackag(res.data); } });
3 效果
动态路由实现了,可是如今还有部分问题未解决
代码在gitee上,能够直接运行。