根据后台返回的路由来显示对应的菜单栏
两种思路,一种是将后台的数据拿到遍历成前端的路由格式,另一种是前端写一份路由,拿到后台的数据进行比对,然后筛选出需要的路由进行展示。
这两种方式思路都一样,将拿到的后台数据进行递归改造,然后router.addRoutes(),将新的动态路由添加进去即可。
1 /** 2 * 后台查询的菜单数据拼装成路由格式的数据 3 * @param route [] 7 * @param {arr} clientAsyncRoutes 前端保存动态路由 8 * @param {arr} serverRouter 后端保存动态路由 9 */ 10 function generaMenu(route, serverRouter, clientAsyncRoutes) { 11 state.menu = {} 12 serverRouter.map((ele, index) => { 13 for (let i = 0; i < clientAsyncRoutes.length; i++) { 14 if (clientAsyncRoutes[i].name === serverRouter[index].name) { 15 state.menu = { 16 path: clientAsyncRoutes[i].path, 17 component: clientAsyncRoutes[i].component, 18 // hidden: true, 19 name: clientAsyncRoutes[i].name + ‘_‘ + serverRouter[index].id, 20 meta: serverRouter[index].name === ‘Home‘ ? ‘‘ : { title: clientAsyncRoutes[i].meta.title, icon: clientAsyncRoutes[i].meta.icon }, 21 children: serverRouter[index].name === ‘Home‘ ? clientAsyncRoutes[i].children : [] 22 } 23 route.push(state.menu) 24 if (serverRouter[index].subData.length > 0) { 25 generaMenu(state.menu.children, serverRouter[index].subData, clientAsyncRoutes[i].children) 26 } 27 } 28 } 29 }) 30 }
可根据具体需求 来配置具体的路由格式
下面是我项目中的路由
1 import Layout from ‘@/layout‘ 2 3 const eventOperationRouter = { 4 path: ‘/eventOperation‘, 5 component: Layout, 6 redirect: ‘/eventOperation/banner/index‘, 7 name: ‘eventOperation‘, 8 meta: { 9 title: ‘Event Operation‘, 10 icon: ‘iconfont icon-icon-event‘ 11 }, 12 children: [ 13 { 14 path: ‘banner‘, 15 component: () => import(‘@/views/eventOperation/banner/index‘), // Parent router-view 16 name: ‘Banner‘, 17 meta: { 18 title: ‘Banner‘ 19 } 20 }, 21 { 22 path: ‘‘ 23 } 24 ] 25 } 26 export default eventOperationRouter
部分后台返回的数据格式
原文:https://www.cnblogs.com/nanabing/p/13323442.html