vue-admin-template 角色权限设置(1)

一、动态路由配置

当我们需要根据用户登陆角色来控制路由权限的时候,可以通过动态路由来解决。

1 划分路由

  • constantRoutes 在所有的角色页面上都会显示
  • asyncRoutes 路由会根据路由的 meta 参数中的 roles 进行角色权限限制
export const constantRoutes = [
  {
    path: '/login',
    component: () => import('@/views/login/index'),
    hidden: true
  },
  ...
]

// meta 中的 roles 可以根据实际情况进行配置
export const asyncRoutes = [
  {
    path: '/service',
    component: Layout,
    redirect: '/service',
    name: 'Service',
    meta: { title: '业务管理', icon: 'el-icon-monitor', roles: ['admin', 'casher'] },
    children: [
      {
        path: 'order',
        name: 'Order',
        component: () => import('@/views/order/index'),
        meta: { title: '项目预约', icon: 'el-icon-s-order', roles: ['admin', 'casher'] }
      },
      {
        path: 'checkout',
        name: 'Checkout',
        component: () => import('@/views/checkout/index'),
        meta: { title: '前台收银', icon: 'el-icon-wallet', roles: ['admin', 'casher'] }
      }
    ]
  },
  ...
]

2 修改 src/permission.js

  • 通过 getInfo 判断用户是否获得了权限角色
  • 注意:roles 必须是数组形式,如 ['xxx'] or ['xx','xxx']
  • 根据角色生成可访问的路由,然后动态生成可访问的路由
import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login'] // no redirect whitelist

router.beforeEach(async(to, from, next) => {
  // start progress bar
  NProgress.start()

  // set page title
  document.title = getPageTitle(to.meta.title)

  // determine whether the user has logged in
  const hasToken = getToken()

  if (hasToken) {
    if (to.path === '/login') {
      // if is logged in, redirect to the home page
      next({ path: '/' })
      NProgress.done()
    } else {
      // determine whether the user has obtained his permission roles through getInfo
      const hasRoles = store.getters.roles && store.getters.roles.length > 0
      if (hasRoles) {
        next()
      } else {
        try {
          // get user info
          // note: roles must be a object array! such as: ['admin'] or ,['developer','editor']
          const { roles } = await store.dispatch('user/getInfo')

          // generate accessible routes map based on roles
          const accessRoutes = await store.dispatch('permission/generateRoutes', roles)

          // dynamically add accessible routes
          router.addRoutes(accessRoutes)

          // hack method to ensure that addRoutes is complete
          // set the replace: true, so the navigation will not leave a history record
          next({ ...to, replace: true })
        } catch (error) {
          // remove token and go to login page to re-login
          await store.dispatch('user/resetToken')
          Message.error(error || 'Has Error')
          next(`/login?redirect=${to.path}`)
          NProgress.done()
        }
      }
    }
  } else {
    /* has no token*/

    if (whiteList.indexOf(to.path) !== -1) {
      // in the free login whitelist, go directly
      next()
    } else {
      // other pages that do not have permission to access are redirected to the login page.
      next(`/login?redirect=${to.path}`)
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})

3 新增 src/store/modules/permission.js

  • 用于管理异步路由
  • 利用 meta 和 roles 进行匹配过滤异步路由
import { asyncRoutes, constantRoutes } from '@/router'

/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role))
  } else {
    return true
  }
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, roles) {
  const res = []
  routes.forEach(route => {
    const tmp = { ...route }
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles)
      }
      res.push(tmp)
    }
  })
  return res
}

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  }
}

const actions = {
  generateRoutes({ commit }, roles) {
    return new Promise(resolve => {
      let accessedRoutes
      if (roles.includes('admin')) {
        accessedRoutes = asyncRoutes || []
      } else {
        accessedRoutes = filterAsyncRoutes(asyncRoutes, roles)
        console.log(accessedRoutes)
      }
      commit('SET_ROUTES', accessedRoutes)
      resolve(accessedRoutes)
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

需要在 src/store/modules/index.js 中添加 permission

import Vue from 'vue'
import Vuex from 'vuex'
import getters from './getters'
import app from './modules/app'
import settings from './modules/settings'
import user from './modules/user'
import tagsView from './modules/tagsView'
import permission from './modules/permission'

Vue.use(Vuex)

const store = new Vuex.Store({
  modules: {
    app,
    settings,
    user,
    tagsView,
    permission
  },
  getters
})

export default store

4 修改 src/store/modules/user.js

  • 新增 roles 属性
  • 添加 set_roles 的函数
  • 对于 getInfo 的 action 在函数中需要获取后台传递过来的 roles 参数
import { login, logout, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'
import store from './../index'

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: '',
    roles: []
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: password}).then(response => {
        const { data } = response
        commit('SET_TOKEN', data.token)
        setToken(data.token)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(response => {
        const { data } = response
        if (!data) {
          return reject('Verification failed, please Login again.')
        }

        const { name, roles, avatar } = data
        if (!roles || roles.length <= 0) {
          reject('getInfo:roles must be a non-null array!')
        }
        commit('SET_NAME', name)
        commit('SET_ROLES', roles)
        commit('SET_AVATAR', avatar)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        removeToken() // must remove  token  first
        resetRouter()
        commit('RESET_STATE')
        commit('SET_ROLES', [])
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

5 修改 src/store/getters.js

  • 新增 roles 和 permission_routes

// 新增 roles, permission_routes

const getters = {
  sidebar: state => state.app.sidebar,
  device: state => state.app.device,
  token: state => state.user.token,
  avatar: state => state.user.avatar,
  name: state => state.user.name,
  visitedViews: state => state.tagsView.visitedViews,
  cachedViews: state => state.tagsView.cachedViews,
  roles: state => state.user.roles,
  permission_routes: state => state.permission.routes
}
export default getters

6 修改 src/components/Sidebar/index.vue

  • 在 sidebar 上添加 permission_routes
  • 修改原始 template 的 sidebar-item
computed: {
    ...mapGetters([
      'permission_routes',
      'sidebar'
    ]),
   ..........
<sidebar-item v-for="route in permission_routes" :key="route.path" :item="route" :base-path="route.path" />

最后,项目的后端部分需要返回 roles,并且 roles 是以数组的形式出现的,大概需要的字段为:

这里后端实现部分就省略啦~ 到此实现!

二、页面组件的角色权限配置

当我们在同一个页面中需要对某些组件权限进行显示时,可以采用 自定义指令+Storage 来实现
如页面中有增删改查,而当前角色只能进行查看。

1 修改 src/store/modules/user.js 中的 getInfo 方法

  • 根据角色进行操作的存储
  • 注意是数组形式
getInfo({ commit, state }) {
  return new Promise((resolve, reject) => {
    getInfo(state.token).then(response => {
      const { data } = response;
      if (!data) {
        return reject('验证失败,请重新登录!')
      }
      const { name, roles, avatar } = data
      if (!roles || roles.length <= 0) {
        reject('您不是有效的身份!')
      }
      // 将页面级的操作权限存在localStorage里
      if (roles.includes('店长')) {
        localStorage.setItem('permissions', JSON.stringify(['add', 'editAndDelete']));
      } else if (roles.includes('收银员') || roles.includes('技师') || roles.includes('发型师')) {
        localStorage.setItem('permissions', JSON.stringify([]));
      }
      commit('SET_NAME', name)
      commit('SET_ROLES', roles)
      commit('SET_AVATAR', avatar)
      resolve(data)
    }).catch(error => {
      reject(error)
    })
  })
},

2 在 src/directives/has.js 内创建自定义指令

  • 获取操作进行判断
  • 如果没有权限的话,直接将该节点移除
export default {
    bind(el, bindings) {
        // 获取权限
        const permissions = localStorage.getItem('permissions') && JSON.parse(localStorage.getItem('permissions'));
        // 进行权限的判断
        const needPermission = bindings.value;
        const hasPermission = permissions.includes(needPermission)
        // 如果没有权限的话
        if (!hasPermission) {
            // 直接移除
            setTimeout(() => {
                el.parentNode.removeChild(el);
            }, 0)
        }
    }
}

3 在需要的 vue 文件引入自定义指令并使用

import hasDirective from "@/directives/has";
export default {
  name: "xxx",
  directives: {
    has: hasDirective,
  },
  ...
}
<el-button
  type="primary"
  icon="el-icon-plus"
  size="small"
  @click="handleAdd"
  v-has="'add'"
  >新增项目类别
</el-button>

4 特殊情况 el-table-column

在使用的时候我发现在 el-table-column 上使用自定义指令是无效的

原因:在执行自定义指令时该 column 所代表的 dom 节点还未完全生成,在结构中仅仅只有一个根 div,这里需要说的是,element-ui 的这个组件是使用 createElement 动态生成的,而自定义指令在 dom 尚未完全生成之前就已执行,因此无法进行操作。el-table-column 是定义表格列的,列在表格中不是一个元素,在表格中没有一个具体的 el,所以指令会运行,但不会生效。

解决办法

  • 方法一:v-if 来定义 el-table-column 进行判断
  • 方法二:根据权限组合数据,遍历数据生成 el-table-column

这里就不再详细展开说啦~到此都完成啦!

posted @ 2022-05-15 01:19  琪有此理  阅读(1653)  评论(3编辑  收藏  举报