1.登录时获取用户按钮权限;存放在store里;此处存放在store/modules/auth
const state = {
perms: [], // 用户权限标识集合
}
const mutations = {
setPerms(state, perms){ // 用户权限标识集合
state.perms = perms;
}
}
const actions = {
// 获取该用户的按钮权限
getUserBtnPerms({dispatch,commit}){
return new Promise((resolve) =>{
post('/getUserBtnPerms', {
}).then(res => {
// 保存用户权限标识集合
//res.data 返回用户拥有权限的按钮的名称数组 例如 ['user:add']
commit('setPerms', res.data)
})
})
},
}
export default {
namespaced: true,
state,
mutations,
actions
}
2. 新建权限文件,permission.js
import store from '@/store'
/**
* 判断用户是否拥有操作权限
* 根据传入的权限标识,查看是否存在用户权限标识集合
* @param perms
*/
export function hasPermission (perms) {
let hasPermission = 0
let permissions = store.state.auth.perms;
for(let i=0, len=permissions.length; i<len; i++) {
if(permissions[i].perms === perms) {
hasPermission = 1;
break
}
}
return hasPermission
}
3.封装按钮组件
<template>
<el-button :size="size" :type="type" :icon="icon" :loading="loading" :disabled="hasPerms(perms)" @click="handleClick(perms)" @click.stop>
{{label}}
</el-button>
</template>
<script>
import { hasPermission } from '@/permission/index.js'
export default {
name: 'psy-button',
props: {
label: { // 按钮显示文本
type: String,
default: 'Button'
},
icon: { // 按钮显示图标
type: String,
default: ''
},
size: { // 按钮尺寸
type: String,
default: 'medium'
},
type: { // 按钮类型
type: String,
default: null
},
loading: { // 按钮加载标识
type: Boolean,
default: false
},
disabled: { // 按钮是否禁用
type: Boolean,
default: false
},
perms: { // 按钮权限标识,外部使用者传入
type: String,
default: null
}
},
data() {
return {
}
},
methods: {
handleClick: function (perms) {
let p=this.hasClickPerms(perms)
if(p==1){//此处可以进行一些提示信息需求的处理
// 按钮操作处理函数
this.$emit('click', {})
}else{
}
},
hasClickPerms: function (perms) {
// 根据权限标识和外部指示状态进行权限判断
return hasPermission(perms)
},
hasPerms: function (perms) {
// 根据权限标识和外部指示状态进行权限判断
let p=hasPermission(perms)==0;
return p || this.disabled
}
},
mounted() {
}
}
</script>
<style scoped>
</style>
4. 页面使用
<psy-button type="primary" perms="user:add" label="新增用户" @click="addUser"/>
import psy_button from "@/components/psy_button"
components: {
'psy-button':psy_button
}