其他分享
首页 > 其他分享> > vue-admin-template角色权限设置

vue-admin-template角色权限设置

作者:互联网

1 动态路由配置


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

1.1 划分路由

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'] }
      }
    ]
  },
  ...
]

1.2 修改 src/permission.js

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()
})

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

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

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

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
}

1.5 修改 src/store/getters.js


// 新增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

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

computed: {
    ...mapGetters([
      'permission_routes',
      'sidebar'
    ]),
   ..........
<sidebar-item v-for="route in permission_routes" :key="route.path" :item="route" :base-path="route.path" />

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

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

2 页面组件的角色权限配置


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

2.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.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)
        }
    }
}

2.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>

2.4 特殊情况 el-table-column

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

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

解决办法

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

标签:vue,const,roles,admin,token,state,user,template,import
来源: https://www.cnblogs.com/sevenkiki/p/16272110.html