Vue background management projects often have permission control, different roles use different permissions, the common method is to use addRoutes to dynamically addRoutes, but there are two problems can not find solutions on the official documents

  • During role switchover, addRoutes displays a message indicating that there are duplicate routes and the routes of the previous role cannot be deleted
  • The dynamic route disappears, and 404 is displayed

Common Solutions

The common solution on the Internet is to refresh the page when the role is switched, so that the previous route disappears. During the normal page refresh, the routing information is stored in localStorage, read the routing information in router.beforeEach, and add it to addRoutes.

First of all, the experience is general, switch page refresh operation, there will be obvious page flashing, localStorage routing information is not good, it is easy to modify, not safe

The ultimate solution

  • When switching roles, create a new Newrouter and override the original router.matcher with the new newrouter. matcher

    /** * add router/index.js with $addRoutes ($addRoutes); /** * Add router/index.js with $addRoutes ($addRoutes); Methods from a lot of issues, https://github.com/vuejs/vue-router/issues/2886 * /
    const constantRouterMap = [] // Default routing rules, such as the login page (non-permission page)
    router.$addRoutes = (params) = > {
      router.matcher = new VueRouter({ // Reset the routing rule
        routes: constantRouterMap
      }).matcher
      router.addRoutes(params) // Add a route
    }
    Copy the code
  • When refreshing the page, add a dynamic route to router.onReady. After the page is refreshed and the route is loaded, the router.onReady method will be executed. Execute only once after refreshing

    /** * the onReady method can read the official document without further details */
      
    router.onReady(() = > {
      const status = true // Check that the user is logged in and has permissions
      if (status) {
        store.dispatch('getJurisdiction') // Request dynamic routing
          .then(e= > {
            router.addRoutes(e.list) $addRoutes = $addRoutes; $addRoutes = $addRoutes})}})Copy the code

Matters needing attention

404 page flash problem, if the 404 page is in the default route, refresh the page while the dynamic route is loading, the page will briefly display 404, the solution is to load the 404 page in the dynamic route, that is, after obtaining the dynamic route, push the 404 page, so that the perfect solution

Have a question welcome message!


2021/08/16 update

Router. addRoutes is not recommended in vue-Router 3.5.0. Router. addRoutes is not recommended in vue-Router 4.x. Only router.addRoute can be used