基于vue的前端页面按钮权限控制
来源 https://www.jianshu.com/p/e50633a9005e前端框架是基于vue-element-admin的项目地址 https://github.com/PanJiaChen/vue-element-admin实现思路就是从后台根据用户查询用户所分配的所有按钮权限 每一个按钮都有标识然后放进store中定义全局变量 在页面按钮做匹配,判断...
·
来源 https://www.jianshu.com/p/e50633a9005e
前端框架是基于vue-element-admin的
项目地址 https://github.com/PanJiaChen/vue-element-admin
实现思路就是从后台根据用户查询用户所分配的所有按钮权限 每一个按钮都有标识
然后放进store中
定义全局变量 在页面按钮做匹配,判断按钮传入的是否在store中存在 存在就显示 不存在就不显示.具体实现步骤如下
标红部分代码是关于前端按钮部分的
文件地址 src/store/modules/user.js
import { login, logout, getInfo } from '@/api/user' import { getToken, setToken, removeToken } from '@/utils/auth' import router, { resetRouter } from '@/router' import { setStore, getStore, removeStore } from '@/utils/store' const state = { token: getToken(), name: '', avatar: '', introduction: '', buttons: [], roles: [], isLock: getStore({ name: 'isLock' }) || false, lockPasswd: getStore({ name: 'lockPasswd' }) || '' } const mutations = { SET_TOKEN: (state, token) => { state.token = token }, SET_INTRODUCTION: (state, introduction) => { state.introduction = introduction }, SET_DEPTID: (state, deptId) => { state.deptId = deptId }, SET_NAME: (state, name) => { state.name = name }, SET_AVATAR: (state, avatar) => { state.avatar = avatar }, SET_BUTTONS: (state, buttons) => { state.buttons = buttons }, SET_ROLES: (state, roles) => { state.roles = roles }, SET_LOCK_PASSWD: (state, lockPasswd) => { state.lockPasswd = lockPasswd setStore({ name: 'lockPasswd', content: state.lockPasswd, type: 'session' }) }, SET_LOCK: (state, action) => { state.isLock = true setStore({ name: 'isLock', content: state.isLock, type: 'session' }) }, CLEAR_LOCK: (state, action) => { state.isLock = false state.lockPasswd = '' removeStore({ name: 'lockPasswd' }) removeStore({ name: 'isLock' }) } } const actions = { // user login login({ commit }, userInfo) { const username = userInfo.username.trim() const validateCode = userInfo.validateCode.trim() return new Promise((resolve, reject) => { login(username, userInfo.password, validateCode).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) { reject('Verification failed, please Login again.') } const { roles, name, avatar, introduction, deptId, buttons } = data // roles must be a non-empty array if (!roles || roles.length <= 0) { reject('getInfo: roles must be a non-null array!') } const buttonAuthList = [] buttons.forEach(button => { if (button.perms) { buttonAuthList.push(button.perms) } }) // alert(JSON.stringify(buttonAuthList) + '--' + buttonAuthList.length) commit('SET_ROLES', roles) commit('SET_NAME', name) commit('SET_AVATAR', avatar) commit('SET_INTRODUCTION', introduction) commit('SET_DEPTID', deptId) commit('SET_BUTTONS', buttonAuthList) resolve(data) }).catch(error => { reject(error) }) }) }, // user logout logout({ commit, state }) { return new Promise((resolve, reject) => { logout(state.token).then(() => { commit('SET_TOKEN', '') commit('SET_ROLES', []) commit('SET_BUTTONS', []) removeToken() resetRouter() resolve() }).catch(error => { reject(error) }) }) }, // remove token resetToken({ commit }) { return new Promise(resolve => { commit('SET_TOKEN', '') commit('SET_ROLES', []) commit('SET_BUTTONS', []) removeToken() resolve() }) }, // dynamically modify permissions changeRoles({ commit, dispatch }, role) { return new Promise(async resolve => { const token = role + '-token' commit('SET_TOKEN', token) setToken(token) const { roles } = await dispatch('getInfo') resetRouter() // generate accessible routes map based on roles const accessRoutes = await dispatch('permission/generateRoutes', roles, { root: true }) // dynamically add accessible routes router.addRoutes(accessRoutes) // reset visited views and cached views dispatch('tagsView/delAllViews', null, { root: true }) resolve() }) } } export default { namespaced: true, state, mutations, actions }
文件地址 : src/store/getters.js
const getters = {
sidebar: state => state.app.sidebar,
language: state => state.app.language,
size: state => state.app.size,
device: state => state.app.device,
visitedViews: state => state.tagsView.visitedViews,
cachedViews: state => state.tagsView.cachedViews,
token: state => state.user.token,
avatar: state => state.user.avatar,
name: state => state.user.name,
deptId: state => state.user.deptId,
introduction: state => state.user.introduction,
roles: state => state.user.roles,
buttons: state => state.user.buttons,
permission_routes: state => state.permission.routes,
isLock: state => state.user.isLock,
lockPasswd: state => state.user.lockPasswd,
errorLogs: state => state.errorLog.logs
}
export default getters
路径 src/utils/permission.js
import store from '@/store'
/**
* @param {Array} value
* @returns {Boolean}
* @example see @/views/permission/directive.vue
*/
export default function checkPermission(value) {
if (value && value instanceof Array && value.length > 0) {
const roles = store.getters && store.getters.roles
const permissionRoles = value
const hasPermission = roles.some(role => {
return permissionRoles.includes(role)
})
if (!hasPermission) {
return false
}
return true
} else {
console.error(`need roles! Like v-permission="['admin','editor']"`)
return false
}
}
// 用来控制按钮的显示
export function hasBtnPermission(permission) {
const myBtns = store.getters.buttons
return myBtns.indexOf(permission) > -1
}
文件路径 src/main.js
import Vue from 'vue' import Cookies from 'js-cookie' import 'normalize.css/normalize.css' // a modern alternative to CSS resets import Element from 'element-ui' import './styles/element-variables.scss' import '@/styles/index.scss' // global css import App from './App' import store from './store' import router from './router' import i18n from './lang' // internationalization import './icons' // icon import './permission' // permission control import './utils/error-log' // error log import * as filters from './filters' // global filters import { hasBtnPermission } from './utils/permission' // button permission /** * If you don't want to use mock-server * you want to use MockJs for mock api * you can execute: mockXHR() * * Currently MockJs will be used in the production environment, * please remove it before going online! ! ! */ // import { mockXHR } from '../mock' // if (process.env.NODE_ENV === 'production') { // mockXHR() // } Vue.use(Element, { size: Cookies.get('size') || 'medium', // set element-ui default size i18n: (key, value) => i18n.t(key, value) }) // register global utility filters Object.keys(filters).forEach(key => { Vue.filter(key, filters[key]) }) Vue.config.productionTip = false Vue.prototype.hasPerm = hasBtnPermission new Vue({ el: '#app', router, store, i18n, render: h => h(App) })
接下来就是页面调用了
<!--列表-->
<el-table class="table-data" :data="posts" highlight-current-row style="width: 100%;" @selection-change="selsChange">
<el-table-column type="selection" width="55" />
<el-table-column prop="postCode" label="岗位编码" width="300" />
<el-table-column prop="postName" label="岗位名称" width="450" />
<el-table-column prop="postSort" label="显示顺序" width="150" />
<el-table-column prop="status" label="状态" width="150">
<template slot-scope="scope">
<span v-if="scope.row.status==='0'" class="row-status color-green">正常</span>
<span v-if="scope.row.status==='1'" class="row-status color-red">停用</span>
</template>
</el-table-column>
<el-table-column prop="createTime" label="创建时间" min-width="150" />
<el-table-column label="操作" width="200">
<template slot-scope="scope">
<el-button v-if="hasPerm('system:post:edit')" size="small" @click="handleEdit(scope.$index, scope.row)"><i class="el-icon-edit" />编辑</el-button>
<el-button v-if="hasPerm('system:post:remove')" type="danger" size="small" @click="handleDel(scope.$index, scope.row)"><i class="el-icon-delete" />删除</el-button>
</template>
</el-table-column>
</el-table>
更多推荐
已为社区贡献1条内容
所有评论(0)