permission.js 1.4 KB
Newer Older
1
import { asyncRoutes, constantRoutes } from '@/router'
P
Pan 已提交
2

P
Pan 已提交
3 4 5 6 7
/**
 * 通过meta.role判断是否与当前用户权限匹配
 * @param roles
 * @param route
 */
P
Pan 已提交
8
function hasPermission(roles, route) {
P
Pan 已提交
9
  if (route.meta && route.meta.roles) {
10
    return roles.some(role => route.meta.roles.includes(role))
P
Pan 已提交
11 12 13 14 15
  } else {
    return true
  }
}

16 17
/**
 * 递归过滤异步路由表,返回符合用户角色权限的路由表
18
 * @param routes asyncRoutes
19 20
 * @param roles
 */
21
export function filterAsyncRoutes(routes, roles) {
22 23 24 25 26 27
  const res = []

  routes.forEach(route => {
    const tmp = { ...route }
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
28
        tmp.children = filterAsyncRoutes(tmp.children, roles)
P
Pan 已提交
29
      }
30
      res.push(tmp)
P
Pan 已提交
31 32
    }
  })
33 34

  return res
35 36
}

P
Pan 已提交
37 38
const permission = {
  state: {
39 40
    routes: [],
    addRoutes: []
P
Pan 已提交
41 42
  },
  mutations: {
43 44 45
    SET_ROUTES: (state, routes) => {
      state.addRoutes = routes
      state.routes = constantRoutes.concat(routes)
P
Pan 已提交
46 47 48 49
    }
  },
  actions: {
    GenerateRoutes({ commit }, data) {
P
Pan 已提交
50
      return new Promise(resolve => {
P
Pan 已提交
51
        const { roles } = data
52
        let accessedRoutes
53
        if (roles.includes('admin')) {
54
          accessedRoutes = asyncRoutes
55
        } else {
56
          accessedRoutes = filterAsyncRoutes(asyncRoutes, roles)
57
        }
58 59
        commit('SET_ROUTES', accessedRoutes)
        resolve(accessedRoutes)
P
Pan 已提交
60
      })
P
Pan 已提交
61 62
    }
  }
P
Pan 已提交
63
}
P
Pan 已提交
64

P
Pan 已提交
65
export default permission