Realization of background system permission control based on Vue

Background system permission control based on Vue.js 2.x series + Element UI

Foreword: Those things about vue permission routing...

Project background: There is a background management system, and there are two types of personnel

①Super administrator (called admin), ②Ordinary user (called editor)

Each type of person sees different operation bars and can perform different operations, so the program needs to deal with each permission issue.

The process is difficult to say, not easy to say

vue permissions

【Confused early stage】

I went to Baidu and Google and searched a lot about permissions. Maybe the benevolent sees the benevolent and the wise sees the wisdom. The various introductions make me even more confused, and I really don’t know where to start:

1) Let the backend return json data about permissions, but I don't know how to deal with such data;

2) It is processed in the front-end routing, but I don't know how to use which attributes to achieve this function;

【finally】

Finally, I saw an article
Touching your hands and taking you with Vue . , there is no way to study it carefully.

Specific implementation ideas

1 When creating a vue instance, mount vue-router, but at this time vue-router mounts some login or public pages without permission.

2 When the user logs in, obtain the role, compare the role and the required permissions of each page of the routing table, and generate a routing table accessible to the end user.

3 Call router.addRoutes(store.getters.addRouters) to add user-accessible routes.

4 Use vuex to manage the routing table and render the sidebar components according to the routes accessible in vuex.

It doesn't matter if I'm a little confused, I'll try to explain each step in simple words

1 In the routing router.js, declare the route with the permission of admin (asyncRouterMap for the asynchronously mounted route)

// router.js
import Vue from 'vue'
import Router from 'vue-router'

Vue.use(Router)

export const constantRouterMap = [
  {
    path: '/',
    redirect: '/login',
    hidden: true
  },
  {
    path: '/login',
    name: '登录页面',
    hidden: true,
    component: resolve => require(['../views/login/Login.vue'], resolve)
  },
  {
    path: '/Readme',
    // name: 'Readmehome',
    index: 'Readme',
    meta: {
      title: 'Readme',
      icon: 'el-icon-menu'
    },
    component: resolve => require(['../components/common/Home.vue'], resolve),
    children: [
      {
        name: 'Readme',
        path: '/',
        meta: { title: 'Readme', icon: 'el-icon-menu' },
        component: resolve => require(['../components/page/Readme.vue'], resolve)
      }
    ]
  }
]

export default new Router({
  routes: constantRouterMap
})
// 异步挂载的路由
// 动态需要根据权限加载的路由表
export const asyncRouterMap = [
  {
    path: '/permission',
    // name: 'permissionhome',
    meta: {
      title: 'permission',
      icon: 'el-icon-setting',
      roles: ['admin']
    },
    component: resolve => require(['../components/common/Home.vue'], resolve),
    children: [
      {
        name: 'permission',
        path: '/permission',
        meta: {
          title: 'permission', icon: 'el-icon-menu', roles: ['admin']
        },
        component: resolve => require(['../components/page/permission.vue'], resolve)
      }
    ]
  },
  { path: '*', redirect: '/404', hidden: true }
]

Here, according to the method officially recommended by vue-router , we use the meta tag to indicate which permissions the page can access. For example, meta: { role: ['admin','super_editor'] } means that only admin and super editors can enter the page.

Note: One thing that needs to be paid attention to here is that the 404 page must be loaded last. If 404 is declared together with the constantRouterMap, all subsequent pages will be blocked to 404. For details, see addRoutes when you've got a wildcard route for 404s does not work

2 When the user logs in, get the role, compare the role and the required permissions of each page of the routing table, call router.addRoutes (store.getters.addRouters) to add user-accessible routes, and generate end-user-accessible routes surface. The routing table exists in vuex

permission.js

// permission.js
import router from './router'
import store from './store'
import { Message } from 'element-ui'
import { getToken } from '@/utils/auth' // 验权

const whiteList = ['/login', '/authredirect'] // 不重定向白名单

router.beforeEach((to, from, next) => {
  if (getToken()) { // 判断是否有token
    if (to.path === '/login') {
      next({ path: '/' })
    } else {
      if (store.getters.roles.length === 0) {
        console.log('roles====0')
        store.dispatch('GetInfo').then(res => { // 拉取用户信息
          const roles = res.data.roles // note: roles must be a array! such as: ['editor','develop']
          console.log('roles?', roles)
          store.dispatch('GenerateRoutes', { roles }).then(() => { // 根据roles权限生成可访问的路由表
            console.log('addrouters', store.getters.addRouters)
            router.addRoutes(store.getters.addRouters) // 动态添加可访问路由表
            next({ ...to, replace: true }) // hack方法 确保addRoutes已完成 ,set the replace: true so the navigation will not leave a history record
          })
        }).catch(() => {
          store.dispatch('FedLogOut').then(() => {
            Message.error('验证失败,请重新登录')
            next({ path: '/login' })
          })
        })
      } else {
        console.log('====1')
        next() // 当有用户权限的时候,说明所有可访问路由已生成 如访问没权限的全面会自动进入404页面
      }
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      next('/login')
    }
  }
})

3 Use vuex to manage the routing table and render the sidebar component (menu) according to the routes accessible in vuex.

sidebar

Last preview link

Permission system implemented by vue

Source code download

https://github.com/mgbq/vue-permission

A heartfelt thank you

reward

Finally, if there is something wrong, please correct me

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325816227&siteId=291194637