preface

Has recently been busy with a use vue for rights management projects, in fact, before this, I also studied how to implement the limits of the vue, and also wrote a blog for it, but when the real application in the project, or found many problems, so this article will be with me in the project are some of the problems, and take it out and share with you Of course, the sample code is still in my Github repository, Ant-Design-VUE-ms.

Permission problem Solution

For a project separated from the front and back ends, permissions are no longer controlled only by the back end, which can only control the permissions of the interface, and we still need to control the page display of the front end. For the PROJECT of VUE, first of all, I think that when the permissions are few and all are single permissions, There is no need to use the addRoutes method provided in vUE. Instead, we can use dynamic components, which we can fine-tune according to the roles returned from the back end. Dynamic components are the built-in components provided in VUE

<component :is="currentComponent"/>
Copy the code

Believe to see here, familiar with the students should have to think of it, so, we don’t need to use vuex, routing configuration, and so on complex problems, and returned on pure background character name can solve all the problems, see here feel the contents of these today, don’t worry, there are “good”.

Problems in permission Settings

Can solve the problem of some simple access though so, but for a little more complicated application permissions, is enjoyed, when a role too much, and it also contains a mix of role permission, can derive a lot of problems, is also listed here I met some problems, can be thoughtful about the students.

  • In the case of mixed roles, the route redirects of dynamic components actually jump to one page, but mixed roles will definitely jump to pages of different roles in one page, so we may need to write many layers of judgment, and the more mixed permissions, the more difficult it is to judge.
  • Dynamic components have poor scalability, so if we add another permission, we need to add another dynamic component, and if there are mixed permissions, there will be more changes

Therefore, in conclusion, I chose the traditional addRoutes in the end, so surely some students will ask, since this scheme does not work, then why use it. That’s a good question. Dynamic components are an experiment, and until we know we’re wrong and don’t meet our requirements, we’ll know better why we use the traditional addRoutes permission scheme.

Solution to permission problems

So let’s look at some of the “benefits” of addRoutes:

  • One configuration, multiple use, we configured the dynamic routing, no matter how many permissions added later, can be a good display of route jump and so on, and do not need to change the code, only need to add the new role of the module can be.
  • Mixed character’s problems, if similar content layout, we can use a custom command to distinguish to display module, so that if an account at the same time have a lot of role, then include the role of the module will be corresponding displayed, you won’t get you need to determine whether display which module, There is no need to set up a page for a character to display.

I believe that the students who have done permission to the above content or have some experience, and then we should follow the steps step by step, these steps in the above I have github, you can compare.

  1. Global navigation guard Settings, set the global navigation guard here, I think more is for data persistence, as everybody knows, vuex although is very nice, but there will be a refresh data loss situation, so in this case, we use the navigation guards, every time to refresh, to request the backend interface to get the character information.
if (store.getters.roles.length === 0) {
        store
          .dispatch('GetInfo')
          .then(res => {
            const roles = res.data.resultData && res.data.resultData.roles
            store.dispatch('GenerateRoutes'. Router.addroutes (store.getters.addrouters)})}). Catch (() => { store.dispatch('Logout').then(() => {
              next({ path: '/user/login', query: { redirect: to.fullPath } })
            })
          })
      } else {
        next()
      }
Copy the code

Here the code has been simplified, mainly to show you that there will be a role judgment length above, mainly when we do not refresh the situation, the page role information will not be lost, so we do not need to request the background to obtain role information, to save the number of requests. 2. As can be seen from the above code, we first request the role information, and then request the method of generating route’s GenerateRoutes. The method is written in the Action of VUEX. The routes matching the role are filtered out, and the static routes are linked to the filtered dynamic routes

const permission = { state: { routers: constRouterMap, addRouters: [] }, mutations: { SET_ROUTERS: (state, routers) => { state.addRouters = routers state.routers = constRouterMap.concat(routers) } }, actions: GenerateRoutes({commit}, data) {// omit}}}Copy the code
  1. Set up our routing file, this part is put here, mainly because there is a small pit, so it is specially taken out and shared with you
export const constRouterMap = [
    {
        path: '/',
        redirect: '/index',
        component: BasicLayout,
        children: [
            {
                path: '/index',
                name: 'index',
                // route level code-splitting
                // this generates a separate chunk (about.[hash].js) for this route
                // which is lazy-loaded when the route is visited.
                component: () => import(/* webpackChunkName: "about"* /'@/views/About.vue'),
                meta: {
                    title: 'Dashboard'
                }
            },
            {
                path: '/home',
                name: 'home',
                component: () => import(/* webpackChunkName: "home"* /'@/views/Home.vue'),
                meta: {
                    title: 'Form page'
                }
            },
            {
                path: '/pattern',
                name: 'pattern',
                component: () => import(/* webpackChunkName: "pattern"* /'@/views/DesignPattern.vue')
            },
            {
                path: '/map',
                name: 'map',
                component: () => import(/* webpackChunkName: "map"* /'@/views/DataMap.vue'),
                meta: {
                    title: 'Map component'
                }
            },
        ]
    },
    {
        path: '/user',
        redirect: '/login',
        component: UserLayout,
        children: [
            {
                path: '/login',
                name: 'login',
                component: () => import(/* webpackChunkName: "login"* /'@/views/user/Login.vue')
            },
            {
                path: '/register',
                name: 'register',
                component: () => import(/* webpackChunkName: "login"* /'@/views/user/Register.vue'}}, // The route to 404 must be written in the static route {path:'/ 404',
        component: () => import(/* webpackChunkName: "not_found"* /'@/views/NotFound.vue')}]export const asyncRouterMap = [
    {
        path: '/',
        redirect: '/index',
        component: BasicLayout,
        children: [
            {
                path: '/controls',
                name: 'controls',
                component: () => import(/* webpackChunkName: "controls"* /'@/views/Controls.vue'),
                meta: {
                    title: 'Permission Settings',
                    permission: ['admin']}}]}, // Capture undefined route configuration {path:The '*',
        redirect: '/ 404',
        hidden: true}]Copy the code

The order in which 404 pages are defined is very important. If a static route is defined to capture a route path: *, and a dynamic route 404 is defined to capture a route 404, there will be some unexpected errors in the navigation hook judgment. I also made some complicated breadcrumb decisions in the navigation hooks, which would result in the following errors once the page was refreshed

window.location.reload();
this.$router.push({name: 'login'});
Copy the code

This is because the routes generated by addRoutes will always exist without refreshing. Even if the next user of a different role logs in, the route information that existed before will still be filtered. The result of filtering must be that none of the routes of the current role will exist. Therefore, the generated routing information is still the route of the previous role, so do not forget to do these two steps before completing the previous steps, which is also a complete permission solution

The end of the

Above is my some goods in the project, take out and share it with, also hope everybody go less detours, pay attention to each a seemingly small problem we encountered in the development, often is the key to we finally solve the problem, both from the dynamic component and dynamic routing, the emergence of the problem is we have to improve their process.