In , dynamic routing is a function of dynamically changing the routing list based on different user permissions or other factors. This mechanism allows developers to dynamically render front-end routes based on the permission data provided by the back-end, implement a multi-user permission system, and different users display different navigation menus.
Dynamic routing configuration
The configuration of dynamic routing involves dynamic loading and parsing of front-end routing. Generally, dynamically routed data is stored in a database, and the front-end obtains the route list corresponding to the current user through the interface and renders it. Here are the basic steps to implement dynamic routing:
Static routing configuration: First, you need to configure static routing, such as login page, home page, etc. These routes are usually not changed and can be written directly in the routing configuration file.
// Create a routing instanceconst router = createRouter({ history: createWebHistory(.BASE_URL), routes: allRoutes })
// All route definitions (static + dynamic)const allRoutes = [ // Basic routing { path: '/', name: 'login', component: () => import("@/views/") }, { path: '/404', name: '404', component: () => import('@/views/Error/') }, // Dynamic routing container (content after login) { path: '/layout', name: 'layout', component: () => import('@/Layout/'), children: [] // Initially empty, dynamically inject route }, ]
Dynamic routing acquisition: After the user logs in, the front-end calls the back-end interface to obtain the user's corresponding permission type role.
// Routing configuration that requires permission control (flat structure is easier to manage)const dynamicRouteConfigs = [ { path: '/home', // Pay attention to using relative paths name: 'home', component: () => import('@/views/'), meta: { title: 'front page', icon: 'House', roles: ['*'] // * means all logged in users } }, { path: 'user/list', name: 'UserList', component: () => import('@/views/user/'), meta: { title: 'User List', roles: ['1','2'] } }, { path: 'user/role', name: 'UserRole', component: () => import('@/views/user/'), meta: { title: 'Role Management', roles: ['1'] } } ]
Route filtering functions
// Permission filtering method correctionconst filterRoutes = (routes, roles) => { // Recursively process each routing node return (route => { // Get the permission role required for the current route const requiredRoles = ?.roles || [] // Check whether the current route meets the permission requirements const hasPermission = ('*') || (roles + '') // Recursively process subroutine (key modification points) if () { const filteredChildren = filterRoutes(, roles) // Keep valid subroutines: Children are retained only when subroutines exist = ? filteredChildren : undefined } /* Routing retention conditions (core logic): 1. The current route itself has permission or 2. There is a valid subroutine (even if the current route does not have permissions, the parent container is retained if the subroutine has permissions) */ return hasPermission || ( && > 0) }) }
Dynamically add routes, first clear the existing dynamic routes, and then call the function to add routes to add them.
// Dynamically add routes to layoutconst addDynamicRoutes = (roles) => { // Clear existing dynamic routes const layout = ().find(r => === 'layout') (child => { () }) // Filter and add new routes const allowedRoutes = filterRoutes(dynamicRouteConfigs, loginStore().roles); (route => { ('layout', route); }); (allowedRoutes); ('menuPath',(allowedRoutes));//Stored filtered dynamic route ('menuName',(()));//All dynamic routes stored (()); // Make sure 404 is finally processed ({ path: '/:pathMatch(.*)*', redirect: '/404' }) }
Navigation guard part, operation before routing jump.
Obtain the user status storage instance and detect the login status; judge that the user is not logged in and jump to the login page to log in directly; logged in to access the login page to prevent logged in users from repeatedly accessing the login page; dynamic routing injection.
Use() to inject routes; route jump processing, clear old routes (avoid duplication);
//Router Guard Modification Part (router/)(async (to, from, next) => { const store = loginStore() const isLogin = !! // Not logged in status processing if (!isLogin) { return === '/' ? next() : next('/') } // Redirect when logged in but accessing the login page if ( === '/') { return next('/home') } // Dynamic routing loading logic if (!) { try { // Get saved role information directly from the store const userRoles = (userRoles); // If the role information does not exist, an error will be thrown if (!userRoles || === 0) { throw new Error('User role information not obtained') } // Add dynamic routing addDynamicRoutes(userRoles) // Print after adding the route ('Current all routes:', ().map(r => )) // Update load status (true) // Use replace to avoid repeated history recording return next({ ...to, replace: true }) } catch (error) { ('Route loading failed:', error) // Clear the user status and jump to the login page store.$reset() return next('/') } } next() })
Finally, we summarize the entire process and emphasize key points to help users fully understand the working mechanism of route guards and the correct way to implement dynamic route loading.
This is the article about the example code of Vue implementing front-end control of dynamic routing. For more related vue dynamic routing content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!