In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-03 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article shows you the operation process of vue to achieve dynamic routing, the content is concise and easy to understand, it can definitely brighten your eyes. I hope you can get something through the detailed introduction of this article.
Briefly talk about the advantages of the two ways, after all, if you have never done it, no matter how much you can't understand, you still have to look at the code.
Front-end control
Without back-end help, routing tables are maintained at the front end
The logic is relatively simple and easy to use.
Back-end control
It's a little safer.
The routing table is maintained in the database
Front-end control
Idea: in the route configuration, through the meta attribute, expand the fields related to permissions, and judge the permission identification in the route guard to achieve the dynamic increase of routes and page jumps; for example, we add a role field to control the role
Specific plan:
1. Return the role of the front-end user according to the account number of the logged-in user
2. The front end matches the meta.role of the routing table according to the user's role.
3. Talk about matching routes to form accessible routes
Core code logic
1. In the router.js file (write static routes and dynamic routes in router.js respectively)
Import Vue from 'vue'import Router from' vue-router'Vue.use (Router) import Layout from'@ / layout'// constantRoutes static route Mainly login pages, 404 pages, etc. do not need dynamic routing export const constantRoutes = [{path:'/ redirect', component: Layout, hidden: true, children: [{path:'/ redirect/:path*', component: () = > import ('@ / views/redirect/index')]}, {path:'/ login' Component: () = > import ('@ / views/login/index'), hidden: true}, {path:'/ 404), component: () = > import ('@ / views/error-page/404'), hidden: true}, {path:'/ 401), component: () = > import ('@ / views/error-page/401') Hidden: true}] / / asyncRoutes dynamic routing export const asyncRoutes = [{path:'/ permission', component: Layout, redirect:'/ permission/page', alwaysShow: true, name: 'Permission', meta: {title:' Permission', icon: 'lock', / / Core Code Can be traversed by matching roles, so whether to show / / the meaning is admin, editor these two roles This menu can display roles: ['admin',' editor']}, children: [{path: 'page', component: () = > import (' @ / views/permission/page'), name: 'PagePermission', meta: {title:' PagePermission' / / this means that only admin can show roles: ['admin']}}] const createRouter = () = > new Router ({scrollBehavior: () = > ({y: 0}), routes: constantRoutes}) const router = createRouter () / / this is used for reset routing Very useful, do not look at such a few lines of code export function resetRouter () {const newRouter = createRouter () router.matcher = newRouter.matcher} export default router2, store/permission.js (maintain a state in vuex, and control whether the menu is displayed or not by matching roles)
Import {asyncRoutes, constantRoutes} from'@ / router'// is used to match roles with route.meta.role. Function hasPermission (roles, route) {if (route.meta & & route.meta.roles) {return roles.some (role = > route.meta.roles.includes (role))} else {return true} / / this method traverses the route by recursion Route authorized routes to traversal export function filterAsyncRoutes (routes, roles) {const res = [] routes.forEach (route = > {const tmp = {... route} if (hasPermission (roles, tmp)) {if (tmp.children) {tmp.children = filterAsyncRoutes (tmp.children, roles)} res.push (tmp)}) return res} const state = {routes: [] AddRoutes: []} const mutations = {SET_ROUTES: (state, routes) = > {/ / this place maintains two states, one is addRouters One is routes state.addRoutes = routes state.routes = constantRoutes.concat (routes)} const actions = {generateRoutes ({commit}, roles) {return new Promise (resolve = > {let accessedRoutes if (roles.includes ('admin')) {accessedRoutes = asyncRoutes | | []} else {/ / core code) Transfer the route and the acquired role (acquired at the backend) to match accessedRoutes = filterAsyncRoutes (asyncRoutes, roles)} / / send the matching authorized route to set to vuex commit ('SET_ROUTES', accessedRoutes) resolve (accessedRoutes)} export default {namespaced: true, state, mutations, actions} 3, src/permission.js
(create a new routing guard function, which can be in main.js or extract a file)
The main code in this is to check which routes are accessible before you control the route jump. The logic of the jump can be written in this place after logging in.
/ / permission.jsrouter.beforeEach ((to, from, next) = > {if (store.getters.token) {/ / determine whether there is a token if (to.path = ='/ login') {next ({path:'/'}) } else {/ / determine whether the current user has pulled the user_info information if (store.getters.roles.length = 0) {store.dispatch ('GetInfo') .then (res = > {/ / pull info const roles = res.data.role) / / send the acquired role to match to generate an accessible route store.dispatch ('GenerateRoutes', {roles}). Then () = > {/ / dynamically add accessible routing table (core code) Nothing can be done without it) the router.addRoutes (store.getters.addRouters) / / hack method ensures that addRoutes has completed next ({... to, replace: true}) .catch (err = > {console.log (err)) });} else {next () / / when you have user permission, all accessible routes have been generated. If you have no access permission, you will automatically enter the 404 page} else {if (whiteList.indexOf (to.path)! =-1) {/ / in the login-free whitelist and directly enter next () } else {next ('/ login'); / / otherwise all redirect to login page}) 4. Those in the sidebar can take data from vuex to render
The core code is to take the available routing objects from router to render the sidebar, whether it is dynamic loading at the front end or dynamic loading at the back end, this code is the same.
/ / pass the fetched route in a loop as a parameter to the child component / / get the authorized route routes () {return this.$router.options.routes} props: {/ / route object item: {type: Object, required: true}, isNest: {type: Boolean, default: false}, basePath: {type: String Default:''}}
The front end controls the routing, and the logic is relatively simple. The back end only needs to store the user's role, and the front end matches the user's role. But if you add new roles, it will be very painful, each one will be added.
Second, the back-end control routing
The general idea of the back-end control is that the routing configuration is placed in the database table. After the user successfully logs in, the authorized menu is passed to the front end according to the role permissions, and the front end is formatted into the structure of page routing recognition, and then rendered to the page menu.
After the user logs in, the backend directly generates accessible routing data according to the user's role. Note that this place is the data.
The front end transforms the routing structure it needs according to the routing data returned by the back end.
Specific logic:
There are only some static routes in router.js, such as login, 404 and so on.
Sort out a data structure and store it in the table
Get routing data from the back end, write a method of data conversion, and convert the data into accessible routes.
It also maintains a vuex state and stores the converted routes in vuex.
The sidebar also takes data from the route to render.
Because most of the processes behind the front control and back-end control are the same, this place only looks at the previous different processes:
1. Store/permission.js, send a request to get data in vuex GenerateRoutes ({commit}, data) {return new Promise ((resolve, reject) = > {getRoute (data). Then (res = > {/ / convert the acquired data Then save const accessedRouters = arrayToMenu (res.data) accessedRouters.concat in vuex ([{path:'*', redirect:'/ 404 cycles, hidden: true}]) commit ('SET_ROUTERS', accessedRouters) resolve ()}) .catch (error = > {reject (error)})} 2, sort out a data structure Stored in the table / / page routing format {path:'/ form', component: Layout, children: [{path: 'index', name:' Form', component: () = > import ('@ / views/form/index'), meta: {title: 'Form' Icon: 'form'}}]} / / the collated data format / / first-level menu / / parentId is 0 can be used as a first-level menu Id had better be able to choose 4 digits. As for why you know {id: 1300 parentId: 0 title: "menu Management" path: "/ menu" hidden: false component: null hidden: false name: "menu"}, / / second-level menu / / parentId is not 0, you can match parentId with id of first-level menu. Match the push to children {id: 1307 parentId: 1300 title: "submenu" hidden: false path: "menuItem" component: "menu/menuItem" / / to match the local file address with hidden: false name: "menuItem"} 3, write a conversion method Convert the acquired data into router structure export function arrayToMenu (array) {const nodes = [] / / get the top-level node for (let I = 0) I < array.length Exists +) {const row = array [I] / / this exists method is to determine whether there is a child if (! exists (array, row.parentId)) {nodes.push ({path: row.path, / / routing address hidden: row.hidden, / / all true is fine If the backend is not equipped with component: Layout, / / generally it matches the component name: row.name of your file, / / the route name meta: {title: row.title, icon: row.name}, / / title is the displayed name id: row.id / / id redirect of the route: 'noredirect'})} const toDo = Array.from (nodes) while (toDo.length) {const node = toDo.shift () / / get child node for (let I = 0 I < array.length If (row.parentId = = node.id) {const row = array [I] / / parentId equals to the parent if {const child = {path: row.path, name: row.name, hidden: row.hidden, / / core code Because the component of the secondary route needs to match the component: require ('@ / views/' + row.component +'/ index.vue') of the page, meta: {title: row.title, icon: row.name} Id: row.id} if (node.children) {node.children.push (child)} else {node.children = [child]} toDo.push (child)}} return nodes} / / check if there is a child function exists (rows, parentId) {for (let I = 0) I < rows.length; iTunes +) {if (Rows [I] .id = = parentId) return true} return false} the above is the operation process of dynamic routing by vue. Have you learned any knowledge or skills? If you want to learn more skills or enrich your knowledge reserve, you are welcome to follow the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 284
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.