| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103 |
- import Vuex from 'vuex'
- import Vue from 'vue'
- import { asyncRoutes, constantRoutes } from '@/router'
- import { getAuthedUser, setAuthedUser } from '@/utils/auth'
- Vue.use(Vuex)
- const store = new Vuex.Store({
- /* modules: {
- user
- },*/
- getters: {
- // 用户登入状态
- roles: state => state.roles,
- routes: state => state.routes,
- addRoutes: state => state.addRoutes,
- // websocket 连接状态
- socketStatus: state => state.socketStatus
- },
- state: {
- userInfo: null,
- roles: [],
- routes: [],
- addRoutes: [],
- socketStatus: 'Offline'
- },
- mutations: {
- SET_ROUTES: (state, routes) => {
- state.addRoutes = routes
- state.routes = constantRoutes.concat(routes) // 组合路由,将原始路由和权限路由组合生成路由表
- },
- // 更新socket 连接状态
- UPDATE_SOCKET_STATUS(state, status) {
- state.socketStatus = status
- },
- // 更新用户信息
- SET_USER_INFO(state, userInfo) {
- // 保存用户信息到缓存
- setAuthedUser(userInfo)
- state.userInfo = userInfo
- // state.roles = userInfo.roles
- },
- SET_ROLES(state, roles) {
- state.roles = roles
- },
- // 用户退出登入
- USER_LOGOUT(state) {
- state.userInfo = null
- state.roles = []
- }
- },
- // 异步操作
- actions: {
- // 这里就是获取 权限路由 参数roles即是用户信息中返回的roles
- generateRoutes({ commit }, roles) {
- return new Promise(resolve => {
- roles.then(roles => {
- const accessedRoutes = filterAsyncRoutes(asyncRoutes, roles)
- // 更改state
- commit('SET_ROUTES', accessedRoutes)
- resolve(accessedRoutes) // 返回 生成的权限路由表
- })
- })
- },
- getUserRoles({ commit }) {
- /* const { roles, userId, avatarUrl, username } = getAuthedUser()
- commit('SET_ROLES', roles)
- return roles*/
- return new Promise((resolve, reject) => {
- const { roles, userId, avatarUrl, username } = getAuthedUser()
- commit('SET_ROLES', roles)
- resolve(roles)
- })
- }
- }
- })
- function hasPermission(roles, route) {
- if (route.meta && route.meta.roles) {
- return roles.some(role => route.meta.roles.includes(role))
- } else {
- return true
- }
- }
- // 判断在 meta 中定义的 roles 是否包含用户角色返回的 roles
- function filterAsyncRoutes(routes, roles) {
- const res = []
- // 循环定义的asyncRoutes权限的路由表
- for (const route of routes) {
- const tmp = { ...route }
- if (hasPermission(roles, tmp)) {
- if (tmp.children) { // 如果有子项 进行递归过滤
- tmp.children = filterAsyncRoutes(tmp.children, roles)
- }
- // 如果定义的mate中roles包含用户roles中的某一项 则添加到res中
- res.push(tmp)
- }
- }
- return res
- }
- export default store
|