The paper

Before work, I always wanted to personally from zero to build a PC system background template, and because of their work and lazy (emmm is lazy) has not been set up successfully, the outbreak also let me have a good time at a deeper level to understand the effect of the PC background to build a complete, want to see the results recorded.

Scaffold address


Function as follows

- Login/Logout - Permission verification - Page permission - Command permission - Permission Configuration - Dynamic route configurationCopy the code
  • In fact, I copied this part directly from vue-admin, a very mature library on Github, but to be honest, although I know there is such a library, I have never used it. This is a new attempt and the best summary to deepen my own vue bucket.

Reason for recording

  • There are two points that I think are particularly important when talking about PC background systems: first, dynamic routing configuration, and second, loading files on demand. Before I came to maintain the company’s project, I deeply felt the importance of an on-demand loading to the system background, when the project is too large, packaging is very time-consuming

Dynamically Configuring Routes

Routing directory structure

  1. The first step in dynamically configuring routes is to distinguish the asynchronous route from the synchronous route. The first step is to determine the winner in the directory
- router-asyncroutes.js - commonroutes.js-index.js - router-asyncroutes.js - router-asyncroutes.js - commonroutes.js-index.js'./Lyout'// Basic layout components include header aside main const asyncRoutes[{path:'/auth',
    name:'auth'
    meta:{
        ismenu:true// To filter all routes recorded for the side column'admin'.'user'}, Component :Lyout, children:[{}]}]Copy the code

In commonRoutes, we add login,404 and other public pages that do not need to be loaded. At this time, these pages are directly injected into the Router instance. There is nothing special about these pages

import routes from './modules/commonRoutes'Const roter=()=>new Router({routers}) // Init requires only commonRoutesCopy the code

Login page to use vuex

  1. At present, it is very common to use VUEX for data operation. After login, the role returned from the background will be directly judged by the front end, and the permission route will be generated and assigned to the router
// store.js
function filterRoutes(filterRoutes, role) {
  let res = [];
  filterRoutes.forEach(route => {
    const roles = route.meta.roles;
    roles.includes(role) ? res.push(route) : ' '
  })
  return res
}
mutations: {
    addUser(state, userInfo) {
      const accessRoutes = filterRoutes(asyncRoutes, userInfo.role);
      resetRouter()
      router.addRoutes(accessRoutes)
      state.routes = accessRoutes
    }
  }


Copy the code

Vue router has a pit in addRoutes. This function can only be added to the router, but does not override or reset the router. If you do not handle this, you will get infinite Duplicate named Routes definition as shown in the following figure, until your application gets hot

Duplicate named Routes Definition

First of all, this problem is caused by route duplication, and in real scenarios, even if you print console.log(this.$router.options.routes) to find your route, there is no problem. There are two types of this problem

Because the name attribute of path is duplicate

The following is an example of an infrequent occurrence that most people may recognize at a glance

{
    path:'/a',
    name:'name'
},
{
    path:'/b',
    name:'name'
}

Copy the code

Inject the route and clear the route from the wrong location

  1. The first solution to this problem is the following code. Of course, you can mount a new addRoutes on the Router instance and clear it using Matcher before doing so, but it is not recommended
export function resetRouter() {
  const newRouter = createRouter()
  router.matcher = newRouter.matcher // reset router
}
Copy the code

Next, where do you inject and clear routes

  1. : Injected at login time

If the user returns or logs out, the vue instance will remain in its original state. In this case, you will need to inject a and B routes after logging in, while already having routes A and B. Duplicate named Routes Definition appears

Solution: So we need to clean up the traces of previous asyncROutes, i.e. call our resetRouter, before adding routes for authentication

  1. Before injecting the vue instance, inject the peimission. Js authentication logic

Solutions: Since main.js will be executed once when the page jumps, it is quite appropriate to make 404 judgment and authentication operations before injecting the page. In the same way, route traces should also be cleared, and then the current route should be obtained through role or token. It is highly recommended to use syntactic sugar such as asynv await with vuex tenth scent

  • Injection of routing
  1. After the login

The solution

  1. Whether user login, user permission modification and other cases involving user permission route judgment, should be cleared before the addRoutes route, ensure that there is no duplication, no conflict
export function resetRouter() {const newRouter = createRouter() router.matcher = newRouter. Matcher} There are a lot of exceptions that add a method directly to the router instance, which is not reliable, and this is the only place I borrowed vue-admin // back to the addUser functionCopy the code

conclusion

In fact, there are more functions to achieve their own, but I think the PC system background is the most critical point is the control of the authority, according to the load of large amount of function points, the rest of the function points are more features of different projects, more like the icing on the cake function