Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Vue background management how to configure dynamic routing menus

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article introduces the knowledge of "how to configure dynamic routing menus in vue background management". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

Background management configuration dynamic routing menu

Some time ago, I worked on a background management project. Because Super Admin can dynamically change permissions for ordinary administrators, the write-to-death permission routing menu in vue-element-admin is not very suitable for me. I have studied it for a long time and experienced a variety of endless cycles. Finally, I have almost come up with one, which may be a little verbose.

My background is divided into three roles: Super Admin, Enterprise Administrator and ordinary Administrator. Among them, the super administrator can view all the routing menus, and the enterprise administrator also has several fixed menu. therefore, the super administrator and the enterprise administrator are the permissions that I directly configure in the routing menu written at the front end, while the ordinary administrator is not fixed. I need the background to return the data and splice it by myself.

1. First of all, we need to have a login page, a simple one with a username and password and a login button. I use the template of vue-element-admin, which has been written and can be used directly.

2. Create a new js file in the src-api folder to write your login, access to user information, login and other interfaces (you can also replace the previous simulation interface in the api/user.js file).

3. Click the login button, and the login method in store-modules-user.js will be called in this method, as follows:

4. The login method in store-modules-user.js calls its own login interface. Of course, remember to import the file before calling it.

Above is the login, user information and logout interface that I introduced.

5. Store stores the returned token and other data after calling the login API (according to my own needs, because I need user id later, I also save user id in store)

6. Call the getInfo method on the same page. Of course, the API for obtaining user information is also called in this method. This step is to obtain the role of the logged-in user. After the call, the returned user role name is saved in store (I have saved other data, or in that case, save whatever data is needed).

* at that time, I had a bug: when I logged in, the refresh page jumped to the login page, indicating that some key data was not stored. After searching the Internet, token has already used cookie to store it in the browser after logging in and calling the login interface. It should be that I only saved the id in store but not in the browser, resulting in the loss of id as soon as I refreshed, so I used localStorage/sessionStorage to store id. The id that is stored locally in getInfo is stored in store.

7. Because the routing menu of the ordinary administrator is returned to me by the background, in the getInfo method, I also directly call the API to get the routing menu, splice the returned data to generate a complete routing menu, and finally save the routing menu array in store.

Note: at the end of the routing menu, be sure to put 404 in the format: {path:'*', redirect: / 404, hidden: true}, be sure to put it at the end!

8. The next step is to call the getInfo method in store-modules-user.js in src/permission.js, which is no different from the template code, so it won't be described much. In this method, the method of generateRoutes in store-modules-permission.js is called

Let's take a look at this method, which is actually based on the passed role to determine which routing menu it can see. The original method in the template is to compare one by one according to the role and the written routing menu, and finally put the corresponding permission items into an array. My super administrator and ordinary administrator here have fixed permissions and routing menu. so directly apply the code. The ordinary administrator, on the other hand, invokes the array of routing menus stored in store and assigns values to the defined variables.

After that, there is no need to change, and you can test the login.

Here I made a relatively large bug:

When I log in as a normal administrator, the menu looks normal when I go in, but no matter which menu I click, it jumps to 404. After some testing and investigation, I found the solution, which is to add a delay timer to this part of the generateRoutes method.

After that, it runs successfully, but I don't quite understand the specific reason, because what I console.log (accessedRoutes) comes out is also a normal routing menu.

This is the general process of configuring the dynamic routing menu as the first successful configuration experience.

Generate dynamic routing and navigation menus according to permissions

Recently, I am working on a background management project, which involves some menu permission control, which is implemented as follows: (needless to say, go directly to the code)

Router/index.js

Const Home = resolve = > require (['@ / views/common/Home.vue'], resolve); const AAA = resolve = > require (['@ / views/page/AAA.vue'], resolve); const BBB = resolve = > require (['@ / views/pages/BBB.vue'], resolve); const CCC= resolve = > require (['@ / views/pages/CCC.vue'], resolve) Let routes = [{path:'/', component: Home, name: 'homepage', redirect:'/ AAA', hidden: true, mate: {icon:'fa fa-home', index: 'AAA'}, children: [{path:' / AAA', component: AAA, name: 'home'}]}] / / get routes from the server For splicing, all modules are no longer introduced in the form of import, but can only be loaded by require! export const makeRoute = function (items) {let routes = [] For (var I = 0; I

< items.length; i++) { // console.log(items[i]); items[i] = formatRoute(items[i]); if (items[i].children) { //递归处理子路由的component items[i].children = makeRoute(items[i].children); } } return items;}//格式化路由,使component挂载到路由上,生成addRoutes可用的格式const formatRoute = (item) =>

{let route = item; route.component = eval (route.component); return route;} export default routes

Main.js (when the login is successful, the backend returns the authorized route and stores it in the status manager vuex)

Import Vue from 'vue'import App from'. / App'import VueRouter from 'vue-router'import axios from' axios'import store from'. / store'import routes from'. / router/index'import {makeRoute} from'. / router'Vue.use (VueRouter) const router = new VueRouter ({routes}) router.beforeEach ((to, from, next) = > {/ / if the destination route is logged in Restore the user's original state if (to.path = ='/ login') {window.clearInterval (window.interval) Store.commit ('logOut');} let allRoutes = store.getters.allRoutes; let loginStatus = store.getters.loginStatus; / / load routing and module if upon successful login (from.path = =' / login' & & allRoutes! = ='& & loginStatus) {let routesObj = makeRoute (store.getters.allRoutes); router.addRoutes (routesObj) } / / automatically jump when not logged in Note if (to.path! = ='/ login' & & (allRoutes ='|! loginStatus)) {if (sessionStorage.getItem ('userInfo') = null) {next ({path:' / login'})} else {/ / refresh the current page / / reset the store parameter let userInfo = JSON.parse (sessionStorage.getItem ('userInfo')) Store.commit ('setUser', userInfo); if (userInfo.routes) {/ / reload routing and module let routesObj = makeRoute (userInfo.routes); router.addRoutes (routesObj);} next ({path: to.path, query: to.query}) }} else {/ / routed next must exist, otherwise you cannot go to the next page next ();}})

Note: the biggest advantage of this scheme is that you no longer have to use require to introduce each component and mount it to the route.

This is the end of the content of "vue background Management how to configure dynamic routing menu". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

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: 0

*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.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report