index.js 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. import Vuex from 'vuex'
  2. import Vue from 'vue'
  3. import { asyncRoutes, constantRoutes } from '@/router'
  4. import { getAuthedUser, setAuthedUser } from '@/utils/auth'
  5. Vue.use(Vuex)
  6. const store = new Vuex.Store({
  7. /* modules: {
  8. user
  9. },*/
  10. getters: {
  11. // 用户登入状态
  12. roles: state => state.roles,
  13. routes: state => state.routes,
  14. addRoutes: state => state.addRoutes,
  15. // websocket 连接状态
  16. socketStatus: state => state.socketStatus
  17. },
  18. state: {
  19. userInfo: null,
  20. roles: [],
  21. routes: [],
  22. addRoutes: [],
  23. socketStatus: 'Offline'
  24. },
  25. mutations: {
  26. SET_ROUTES: (state, routes) => {
  27. state.addRoutes = routes
  28. state.routes = constantRoutes.concat(routes) // 组合路由,将原始路由和权限路由组合生成路由表
  29. },
  30. // 更新socket 连接状态
  31. UPDATE_SOCKET_STATUS(state, status) {
  32. state.socketStatus = status
  33. },
  34. // 更新用户信息
  35. SET_USER_INFO(state, userInfo) {
  36. // 保存用户信息到缓存
  37. setAuthedUser(userInfo)
  38. state.userInfo = userInfo
  39. // state.roles = userInfo.roles
  40. },
  41. SET_ROLES(state, roles) {
  42. state.roles = roles
  43. },
  44. // 用户退出登入
  45. USER_LOGOUT(state) {
  46. state.userInfo = null
  47. state.roles = []
  48. }
  49. },
  50. // 异步操作
  51. actions: {
  52. // 这里就是获取 权限路由 参数roles即是用户信息中返回的roles
  53. generateRoutes({ commit }, roles) {
  54. return new Promise(resolve => {
  55. roles.then(roles => {
  56. const accessedRoutes = filterAsyncRoutes(asyncRoutes, roles)
  57. // 更改state
  58. commit('SET_ROUTES', accessedRoutes)
  59. resolve(accessedRoutes) // 返回 生成的权限路由表
  60. })
  61. })
  62. },
  63. getUserRoles({ commit }) {
  64. /* const { roles, userId, avatarUrl, username } = getAuthedUser()
  65. commit('SET_ROLES', roles)
  66. return roles*/
  67. return new Promise((resolve, reject) => {
  68. const { roles, userId, avatarUrl, username } = getAuthedUser()
  69. commit('SET_ROLES', roles)
  70. resolve(roles)
  71. })
  72. }
  73. }
  74. })
  75. function hasPermission(roles, route) {
  76. if (route.meta && route.meta.roles) {
  77. return roles.some(role => route.meta.roles.includes(role))
  78. } else {
  79. return true
  80. }
  81. }
  82. // 判断在 meta 中定义的 roles 是否包含用户角色返回的 roles
  83. function filterAsyncRoutes(routes, roles) {
  84. const res = []
  85. // 循环定义的asyncRoutes权限的路由表
  86. for (const route of routes) {
  87. const tmp = { ...route }
  88. if (hasPermission(roles, tmp)) {
  89. if (tmp.children) { // 如果有子项 进行递归过滤
  90. tmp.children = filterAsyncRoutes(tmp.children, roles)
  91. }
  92. // 如果定义的mate中roles包含用户roles中的某一项 则添加到res中
  93. res.push(tmp)
  94. }
  95. }
  96. return res
  97. }
  98. export default store