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

How to realize dynamic loading of Vue components in privilege Management Module

2025-04-03 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

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

This article introduces the relevant knowledge of "how to dynamically load Vue components in the rights management module". 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!

Login status Save

When the user logs in successfully, the login information of the current user needs to be saved locally for later use. The specific implementation is as follows:

Log in to save data successfully

After the login operation is executed successfully, the data is submitted to store through the commit operation. The core code is as follows:

This.postRequest ('/ login', {username: this.loginForm.username, password: this.loginForm.password}). Then (resp= > {if (resp & & resp.status = = 200) {var data = resp.data; _ this.$store.commit ('login', data.msg); var path = _ this.$route.query.redirect; _ this.$router.replace ({path: path = =' /'| path = = undefined?'/ home': path});}}) Store

The core code of store is as follows:

Export default new Vuex.Store ({state: {user: {name: window.localStorage.getItem ('user' | |' []') = = null? 'not logged in': JSON.parse (window.localStorage.getItem ('user' | |' []')) .name, userface: window.localStorage.getItem ('user' | |' []') = = null?': JSON.parse (window.localStorage.getItem ('user' | |' []')) .userface}, mutations: {login (state, user) {state.user = user; window.localStorage.setItem ('user', JSON.stringify (user)) }, logout (state) {window.localStorage.removeItem ('user');})

In order to reduce the trouble, the data after the user's successful login will be saved in localStorage (to prevent the user from losing the data after pressing F5 to refresh), stored in the form of a string, and then converted to json when fetched. When the user logs out and logs in, the data in the localStorage is cleared.

Component dynamic loading

In the rights management module, this is the core of the front end.

Core ideas

After logging in successfully, before entering the home home page, the user sends a request to the server to obtain the current menu information and component information. The server returns a json string based on the current user's role and the resources corresponding to the role, in the following format:

[{"id": 2, "path": "/ home", "component": "Home", "name": "employee profile", "iconCls": "fa fa-user-circle-o", "children": [{"id": null, "path": "/ emp/basic" "component": "EmpBasic", "name": "basic Information", "iconCls": null, "children": [], "meta": {"keepAlive": false, "requireAuth": true}} {"id": null, "path": "/ emp/adv", "component": "EmpAdv", "name": "Advanced data", "iconCls": null, "children": [] "meta": {"keepAlive": false, "requireAuth": true}], "meta": {"keepAlive": false, "requireAuth": true}}]

After getting the string, the front end does two things: 1. Dynamically add json to the current route; 2. Save the data to store, and then each page renders the menu based on the data in store.

The core idea is not difficult, let's take a look at the implementation steps.

Timing of data request

This is very important.

There may be a small partner said that this is so difficult, after the successful login request can not be it? Yes, after logging in successfully, it is OK to request menu resources. After the request arrives, we save it in store for next use, but there will be another problem. If the user successfully logs in, clicks on a sub-page, goes to the sub-page, and then clicks F5 to refresh, it will be GG at this time, because after F5 refresh, the data in store will be gone. And we only request menu resources once when the login is successful. To solve this problem, there are two ways of thinking: 1. Do not save the menu resources to store, but to localStorage, so that the data is still there even after F5 refresh. 2. Load the menu resource once directly in the mounted method of each page.

Because menu resources are very sensitive, it is best not to save them locally, so abandon option 1, but option 2 is a bit of a workload, so I took a step to simplify it by using the navigation guard in the route.

Routing navigation guard

My implementation is as follows: first create an routes array in store, which is an empty array, and then turn on the routing global guard, as follows:

Router.beforeEach ((to, from, next) = > {if (to.name = = 'Login') {next (); return;} var name = store.state.user.name; if (name = =' not logged in') {if (to.meta.requireAuth | | to.name = = null) {next ({path:'/', query: {redirect: to.path}})} else {next () } else {initMenu (router, store); next ();}})

The code here is very short, so let me make a simple explanation:

1. If the page you want to go to is the login page, there is nothing to say about this, just go ahead.

two。 If it is not a login page, I first get the current login status from store. If not, use the requireAuth attribute of the meta attribute in the route to determine whether the page to which you want to go needs to log in. If you need to log in, skip back to the login page. At the same time, the path of the page you are going to go to is passed to the login page as a parameter, so that you can jump to the target page after the login is successful. If you do not need to log in, go directly (in fact). Only the Login page in this project does not need to log in) If you are already logged in, initialize the menu before jumping.

The actions to initialize the menu are as follows:

Export const initMenu = (router, store) = > {if (store.state.routes.length > 0) {return;} getRequest ("/ config/sysmenu"). Then (resp= > {if (resp & & resp.status = = 200) {var fmtRoutes = formatRoutes (resp.data); router.addRoutes (fmtRoutes); store.commit ('initMenu', fmtRoutes);}})} export const formatRoutes = (routes) = > {let fmRoutes = [] Routes.forEach (router= > {let {path, component, name, meta, iconCls, children} = router; if (children & & children instanceof Array) {children = formatRoutes (children) } let fmRouter = {path: path, component (resolve) {if (component.startsWith ("Home")) {require (['.. / components/' + component + '.vue'], resolve)} else if (component.startsWith ("Emp")) {require (['.. / components/emp/' + component + '.vue'] Resolve)} else if (component.startsWith ("Per")) {require (['.. / components/personnel/' + component + '.vue'], resolve)} else if (component.startsWith ("Sal")) {require (['.. / components/salary/' + component + '.vue'] Resolve)} else if (component.startsWith ("Sta")) {require (['.. / components/statistics/' + component + '.vue'], resolve)} else if (component.startsWith ("Sys")) {require (['.. / components/system/' + component + '.vue'], resolve)}}, name: name, iconCls: iconCls, meta: meta Children: children} FmRoutes.push (fmRouter);}) return fmRoutes;}

In the initialization menu, first determine whether the data in the store exists, if so, it means that the jump is a normal jump, rather than the user pressing F5 or entering an address directly in the address bar. Otherwise, load the menu. After getting the menu, first use the formatRoutes method to change the json returned by the server to the format required by router. Here, it is mainly to convert component, because the component returned by the server is a string, but what is needed in router is a component, so we can dynamically load the required components in the formatRoutes method. After the data format is prepared successfully, on the one hand, the data is stored in store, on the other hand, it is dynamically added to the route by using the addRoutes method in routing.

Menu rendering

Finally, in the Home page, get the menu json from store and render it into a menu. The related code can be viewed in Home.vue without going into detail.

The content of "how to dynamically load Vue components in the rights management module" is introduced here. 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

Internet Technology

Wechat

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

12
Report