We use vue to develop a management system with authority. Different menu items are displayed according to different users
Scenario: the front-end menu is not statically written in the vue program, but is dynamically loaded into the vue application from the menu list obtained from the background interface
Ideas: 1. When the login is successful, the background will return to our menu list. At this time, we will insert the route configuration corresponding to this menu in Vue router
2. After the route is configured, add the left menu static effect
3. If the user does not have permission to the menu, but he / she has entered the address of the menu in the address bar of the web page. At this time, we should redirect the page to the home page
Implementation: Here we focus on how to insert a route, which is very simple:
1. Insert this.$router.options.routes[0].children.push(). Here we can check the console.log(this.$router.options).
this.$router.options.routes[0].children.push({// Insert route name: 'map', path: '/map', component: resolve => require(['../page/map'], resolve)// Introduce components with require })
2. When all routes are inserted, call the inserted route. So the route has been registered and can be used normally
this.$router.addRoutes(this.$router.options.routes)// Call addRoutes to add routes
Here I throw an example from a recent project and continue to add routes in the secondary route. You can refer to it if you need it
if (list.indexOf('map/getMapPage') !== -1) { this.$router.options.routes[1].children.push({// Insert route name: 'map', path: '/map', component: resolve => require(['../page/map'], resolve)// Introduce components with require }) } if (list.indexOf('getDeviceList') !== -1 || list.indexOf('getDeviceList') !== -1) { let routerData = { path: '/device', name: 'device', component: resolve => require(['../page/device/content.vue'], resolve), children: [ { path: '/device/basiclist', name: 'basiclist', component: resolve => require(['../page/device/basiclist.vue'], resolve) } ] } if (list.indexOf('getDeviceList') !== -1) { routerData.children.push( { path: '/device/basiclist', name: 'basiclist', component: resolve => require(['../page/device/basiclist.vue'], resolve) }, { path: '/device/basicNew', name: 'basicNew', component: resolve => require(['../page/device/basicNew.vue'], resolve) } ) } if (list.indexOf('getGroupList') !== -1) { routerData.children.push( { path: '/device/grounplist', name: 'grounplist', component: resolve => require(['../page/device/grounpList.vue'], resolve) } ) } this.$router.options.routes[1].children.push(routerData) } this.$router.addRoutes(this.$router.options.routes)// Call addRoutes to add routes