This is the 24th day of my participation in the December Gwen Challenge. Check out the event details: The last Gwen Challenge 2021

Before I made SDK, I also wrote VUE. If there is anything worth saying, I will tell you how I made menu permissions of SAAS system based on VUE, VUE Router and VUEX.

Premise: this is a SAAS system based on VUE, the system needs to do dynamic menu permissions, dynamic button permissions according to the current user, we come to see how to achieve dynamic menu permissions.

Dynamic menu permission implementation idea

First of all, the dynamic menu permission is realized based on Vue Router. To realize the dynamic menu permission, the steps are as follows:

  1. Save a route without permission, such as a login page, stateless home page, etc.
  2. Save a route requiring permission, compare the route with the menu permission tree data sent from the server, and then runrouter.addRoutesMethod, add to the original route, this time can be accessed through the route to the page;
  3. Compare the route with the stateless routepushIn an array, data is transmitted through VUEX. Through two-way binding of data, the complete routing address is applied to menuList to realize the display of routing permissions in the menu on the left.
  4. This relies on the Vue Router’s hook functions — beforeEach and VUEX.

Of course, while doing everything, it is not completely smooth, encountered the main problem is the refresh page 404 problem, how did I solve it.

How to solve the page 404 problem after refreshing

The previous solution is to check whether the route has a matching value. If not, run router.addRoutes to add the route again, the code is as follows:

router.beforeEach((to, from, next) => {
  if (to.matched.length === 0) {
    const menu = JSON.parse(localStorage.getItem('menu'))
    router.addRoutes(recursionRouter(menu, allPermissionsRouter))
    next({ path: to.path, query: to.query })
  } else {
    next()
  }
})
Copy the code

The solution is to execute router.addRoutes under the router.onReady hook as follows:

router.onReady(() => {
    const menu = JSON.parse(localStorage.getItem('menu'))
    router.addRoutes(recursionRouter(menu, allPermissionsRouter))
    next({ path: to.path, query: to.query })
})
Copy the code

Actually have a problem, is the menu access only to the login interface, no single exposure interface, can only lead to side at the time of log back in to menu permission to update, but from a product standpoint, may also not a problem, because the log back in again after switch menu permissions, as if also can be said in the past, the past, just like that.