Blame view

src/store/modules/permission.js 1.5 KB
cf56a6c30   吉鹏   init role permission
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
  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 = []
cf56a6c30   吉鹏   init role permission
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
    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)
    }
  }
feb3d4f57   Adam   auto commit the c...
47
  //根据动作进行判断
cf56a6c30   吉鹏   init role permission
48
49
50
51
52
  const actions = {
    generateRoutes({ commit }, roles) {
      return new Promise(resolve => {
        let accessedRoutes
        if (roles.includes('admin')) {
feb3d4f57   Adam   auto commit the c...
53
          console.log('------------generateRoutes----asyncRoutes-----------', asyncRoutes, roles);
cf56a6c30   吉鹏   init role permission
54
55
56
          accessedRoutes = asyncRoutes || []
        } else {
          accessedRoutes = filterAsyncRoutes(asyncRoutes, roles)
feb3d4f57   Adam   auto commit the c...
57
          accessedRoutes.push({});
cf56a6c30   吉鹏   init role permission
58
59
60
61
62
63
64
65
66
67
68
69
70
        }
        commit('SET_ROUTES', accessedRoutes)
        resolve(accessedRoutes)
      })
    }
  }
  
  export default {
    namespaced: true,
    state,
    mutations,
    actions
  }