Vue中的按钮级权限控制
目录1.背景2.核心3.代码3.1sessionStorage代码3.2自定义指令代码3.3使用指令1.背景今天需要对页面的按钮进行权限控制,主要做法是在角色的权限上维护上哪些按钮可以访问,如下图:登陆后查出用户的权限,配合vue自定义指令实现对dom元素的控制。2.核心1.vue自定义指令2.sessionStorage3.代码3.1sessionStorage代码LocalStore.stor
·
1.背景
今天需要对页面的按钮进行权限控制,主要做法是在角色的权限上维护上哪些按钮可以访问,如下图:登陆后查出用户的权限,配合vue自定义指令实现对dom元素的控制。
2.核心
1.vue自定义指令
2.sessionStorage
3.代码
3.1sessionStorage代码
LocalStore.storeValue = function(key, data){
window.sessionStorage.setItem(key,JSON.stringify(data));
}
LocalStore.getValue = function(key){
return JSON.parse(window.sessionStorage.getItem(key));
}
LocalStore.delValue = function(key){
return window.sessionStorage.removeItem(key);
}
3.2自定义指令代码
import Vue from 'vue'
import AuthContext from '../../utils/AuthContext'
/**
* 参考:
* https://blog.csdn.net/dianwang999/article/details/81004171
* https://www.cnblogs.com/chenmz1995/p/11453228.html
* https://cn.vuejs.org/v2/guide/custom-directive.html
*
* 作用:拥有权限并且满足一定的条件才显示
*
* 用法:
* 在元素上添加v-permission和functionCode="functionCode"(只检验权限)
* 在元素上添加v-permission='表达式'和functionCode="functionCode"(校验权限和表达式)
* v-permission:vue的指令。设置在inserted时器被调用。(inserted被绑定元素插入父节点时调用 (仅保证父节点存在,但不一定已被插入文档中)。
* 通过functionCode查找用户是否拥有该functionCode,functionCode为空时不删除元素
*/
const permission = Vue.directive('permission', {
inserted: function (el, binding, vnode) {
let functionCode = vnode.data.attrs.functionCode;
if (!functionCode) {
return;
}
// 获取页面按钮权限
if (!Vue.prototype.$_checkShow(functionCode)) {
el.parentNode.removeChild(el);
return
}
// 判断是否满足条件
let bindValue = binding.value;
if (Object.prototype.toString.call(bindValue) === '[object Boolean]') {
if (!bindValue) {
el.parentNode.removeChild(el);
return
}
}
}
});
// 权限检查方法
Vue.prototype.$_checkShow = function (functionCode) {
return AuthContext.checkFunctionCode(functionCode);
};
export {permission}
3.3使用指令
3.3.1没有表达式的用法
<el-button
type="primary"
icon="el-icon-plus"
class="mr5"
v-permission //自定义指令
functionCode="ImClientUserAdd" //授权码
@click="handleAdd">新增用户
</el-button>
3.3.2有表达式的用法
<el-button
type="text"
icon="el-icon-arrow-up"
v-permission="scope.row.mainFlag === 1"
functionCode="ImClientUserSetPart"
class="e6a23c"
@click="handlePart(scope.$index, scope.row)">设置兼职
</el-button>
4注意点
1.自定义指令与v-if冲突导致部分元素未删除
解决方式:将v-if换为v-show
参考:https://blog.csdn.net/marendu/article/details/108202467
或者采用 v-permission=“表达式”,上述指令添加表达式实现权限和满足一定条件才显示
![在这里插入图片描述](https://img-blog.csdnimg.cn/20210611163435758.png
更多推荐
已为社区贡献1条内容
所有评论(0)