5.4 权限管理前端开发
5.4.1 src/components
新建ParentView文件夹,并在文件夹中新建index.vue文件。
并在index.vue中加入以下内容:
<template><router-view />
</template>
5.4.2 layout/components/Sidebar/index.vue
routes() {// return this.$router.options.routes//新增内容return this.$router.options.routes.concat(global.antRouter)},
5.4.3 router
在index.js中只留以下内容:
import Vue from 'vue'
import Router from 'vue-router'Vue.use(Router)/* Layout */
import Layout from '@/layout'/*** Note: sub-menu only appear when route children.length >= 1* Detail see: https://panjiachen.github.io/vue-element-admin-site/guide/essentials/router-and-nav.html** hidden: true if set true, item will not show in the sidebar(default is false)* alwaysShow: true if set true, will always show the root menu* if not set alwaysShow, when item has more than one children route,* it will becomes nested mode, otherwise not show the root menu* redirect: noRedirect if set noRedirect will no redirect in the breadcrumb* name:'router-name' the name is used by <keep-alive> (must set!!!)* meta : {roles: ['admin','editor'] control the page roles (you can set multiple roles)title: 'title' the name show in sidebar and breadcrumb (recommend set)icon: 'svg-name'/'el-icon-x' the icon show in the sidebarbreadcrumb: false if set false, the item will hidden in breadcrumb(default is true)activeMenu: '/example/list' if set path, the sidebar will highlight the path you set}*//*** constantRoutes* a base page that does not have permission requirements* all roles can be accessed*/
export const constantRoutes = [{path: '/login',component: () => import('@/views/login/index'),hidden: true},{path: '/',component: Layout,redirect: '/dashboard',children: [{path: 'dashboard',name: 'Dashboard',component: () => import('@/views/dashboard/index'),meta: { title: 'Dashboard', icon: 'dashboard' }}]}// {// path: '/system',// component: Layout,// meta: {// title: '系统管理',// icon: 'el-icon-s-tools'// },// alwaysShow: true,// children: [// {// name: 'sysUser',// path: 'sysUser',// component: () => import('@/views/system/sysUser/list'),// meta: {// title: '用户管理',// icon: 'el-icon-s-custom'// },// },// {// path: 'sysRole',// component: () => import('@/views/system/sysRole/list'),// meta: {// title: '角色管理',// icon: 'el-icon-s-help'// },// },// {// name: 'sysMenu',// path: 'sysMenu',// component: () => import('@/views/system/sysMenu/list'),// meta: {// title: '菜单管理',// icon: 'el-icon-s-unfold'// },// },// {// path: 'assignAuth',// component: () => import('@/views/system/sysMenu/assignAuth'),// meta: {// activeMenu: '/system/sysRole',// title: '角色授权'// },// hidden: true,// }// ]// },// {// path: '/form',// component: Layout,// children: [// {// path: 'index',// name: 'Form',// component: () => import('@/views/form/index'),// meta: { title: 'Form', icon: 'form' }// }// ]// },// {// path: '/nested',// component: Layout,// redirect: '/nested/menu1',// name: 'Nested',// meta: {// title: 'Nested',// icon: 'nested'// },// children: [// {// path: 'menu1',// component: () => import('@/views/nested/menu1/index'), // Parent router-view// name: 'Menu1',// meta: { title: 'Menu1' },// children: [// {// path: 'menu1-1',// component: () => import('@/views/nested/menu1/menu1-1'),// name: 'Menu1-1',// meta: { title: 'Menu1-1' }// },// {// path: 'menu1-2',// component: () => import('@/views/nested/menu1/menu1-2'),// name: 'Menu1-2',// meta: { title: 'Menu1-2' },// children: [// {// path: 'menu1-2-1',// component: () => import('@/views/nested/menu1/menu1-2/menu1-2-1'),// name: 'Menu1-2-1',// meta: { title: 'Menu1-2-1' }// },// {// path: 'menu1-2-2',// component: () => import('@/views/nested/menu1/menu1-2/menu1-2-2'),// name: 'Menu1-2-2',// meta: { title: 'Menu1-2-2' }// }// ]// },// {// path: 'menu1-3',// component: () => import('@/views/nested/menu1/menu1-3'),// name: 'Menu1-3',// meta: { title: 'Menu1-3' }// }// ]// },// {// path: 'menu2',// component: () => import('@/views/nested/menu2/index'),// name: 'Menu2',// meta: { title: 'menu2' }// }// ]// },// {// path: 'external-link',// component: Layout,// children: [// {// path: 'https://panjiachen.github.io/vue-element-admin-site/#/',// meta: { title: 'External Link', icon: 'link' }// }// ]// },// // 404 page must be placed at the end !!!// { path: '*', redirect: '/404', hidden: true }
]const createRouter = () => new Router({// mode: 'history', // require service supportscrollBehavior: () => ({ y: 0 }),routes: constantRoutes
})const router = createRouter()// Detail see: https://github.com/vuejs/vue-router/issues/1234#issuecomment-357941465
export function resetRouter() {const newRouter = createRouter()router.matcher = newRouter.matcher // reset router
}export default router
新建_import_development.js 和_import_production.js 两个文件。
//_import_development.js
module.exports = file => require('@/views/' + file + '.vue').default//_import_production.js
module.exports = file => () => import('@/views/' + file + '.vue')
5.4.4 store/modules/user.js
const getDefaultState = () => {return {token: getToken(),name: '',avatar: '',buttons: [],//新增menus: ''//新增}
}
const mutations = {RESET_STATE: (state) => {Object.assign(state, getDefaultState())},SET_TOKEN: (state, token) => {state.token = token},SET_NAME: (state, name) => {state.name = name},SET_AVATAR: (state, avatar) => {state.avatar = avatar},//新增SET_BUTTONS: (state, buttons) => {state.buttons = buttons},//新增SET_MENUS: (state, menus) => {state.menus = menus}
}
// get user infogetInfo({ commit, state }) {return new Promise((resolve, reject) => {getInfo(state.token).then(response => {const { data } = responseif (!data) {return reject('Verification failed, please Login again.')}const { name, avatar } = datacommit('SET_NAME', name)commit('SET_AVATAR', avatar)//新增commit('SET_BUTTONS', data.buttons)//新增commit('SET_MENUS', data.routers)resolve(data)}).catch(error => {reject(error)})})},
5.4.5 store/getter.js
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,//新增buttons: state => state.user.buttons,//新增menus: state => state.user.menus
}
export default getters
5.4.6 utils
在utils中新建文件夹btn-permission.js。
//btn-permission.js
import store from '@/store'/*** 判断当前用户是否有此按钮权限* 按钮权限字符串 permission*/
export default function hasBtnPermission(permission) {// 得到当前用户的所有按钮权限const myBtns = store.getters.buttons// 如果指定的功能权限在myBtns中, 返回true ==> 这个按钮就会显示, 否则隐藏return myBtns.indexOf(permission) !== -1
}
修改request.js:
config => {// do something before request is sentif (store.getters.token) {// let each request carry token// ['X-Token'] is a custom headers key// please modify it according to the actual situation//将x-token修改为tokenconfig.headers['token'] = getToken()}return config},
5.4.7 views/login/index.vue
用户名和密码只检查长度:
const validateUsername = (rule, value, callback) => {if (value.length < 4) {callback(new Error('Please enter the correct user name'))} else {callback()}}
const validatePassword = (rule, value, callback) => {if (value.length < 6) {callback(new Error('The password can not be less than 6 digits'))} else {callback()}}
5.4.8 main.js
// 新增
import hasBtnPermission from '@/utils/btn-permission'
Vue.prototype.$hasBP = hasBtnPermissionimport formCreate from '@form-create/element-ui'
import FcDesigner from '@form-create/designer'
Vue.use(formCreate)
Vue.use(FcDesigner)
5.4.9 permission.js
替换为下面的内容:
import router from './router'
import store from './store'
import { getToken } from '@/utils/auth'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // 水平进度条提示: 在跳转路由时使用
import 'nprogress/nprogress.css' // 水平进度条样式
import getPageTitle from '@/utils/get-page-title' // 获取应用头部标题的函数
import Layout from '@/layout'
import ParentView from '@/components/ParentView'
const _import = require('./router/_import_' + process.env.NODE_ENV) // 获取组件的方法NProgress.configure({ showSpinner: false }) // NProgress Configuration
const whiteList = ['/login'] // no redirect whitelist
router.beforeEach(async(to, from, next) => {NProgress.start()// set page titledocument.title = getPageTitle(to.meta.title)// determine whether the user has logged inconst hasToken = getToken()if (hasToken) {if (to.path === '/login') {// if is logged in, redirect to the home pagenext({ path: '/' })NProgress.done()} else {const hasGetUserInfo = store.getters.nameif (hasGetUserInfo) {next()} else {try {// get user infoawait store.dispatch('user/getInfo')// 请求获取用户信息if (store.getters.menus.length < 1) {global.antRouter = []next()}const menus = filterAsyncRouter(store.getters.menus)// 1.过滤路由console.log(menus)router.addRoutes(menus) // 2.动态添加路由const lastRou = [{ path: '*', redirect: '/404', hidden: true }]router.addRoutes(lastRou)global.antRouter = menus // 3.将路由数据传递给全局变量,做侧边栏菜单渲染工作next({...to,replace: true})// next()} catch (error) {// remove token and go to login page to re-loginconsole.log(error)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 directlynext()} 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 barNProgress.done()
}) // // 遍历后台传来的路由字符串,转换为组件对象
function filterAsyncRouter(asyncRouterMap) {const accessedRouters = asyncRouterMap.filter(route => {if (route.component) {if (route.component === 'Layout') {route.component = Layout} else if (route.component === 'ParentView') {route.component = ParentView} else {try {route.component = _import(route.component)// 导入组件} catch (error) {debuggerconsole.log(error)route.component = _import('dashboard/index')// 导入组件}}}if (route.children && route.children.length > 0) {route.children = filterAsyncRouter(route.children)} else {delete route.children}return true})return accessedRouters
}
5.4.10 按钮权限控制
在写按钮时按照如下写法即可:
<el-button type="danger" icon="el-icon-delete" size="mini" @click="removeDataById(scope.row.id)" title="删除" :disable="$hasBP('bnt.sysUser.remove')===false"/>