之前写一个 demo,直接移除 dom 元素可能比 display="none"好一点
<template>
<div>
<v-btn color="primary">正常按钮</v-btn>
<!--arg:role,function modifiers:all any default:any -->
<v-btn color="success" v-permission:function.all="permission">权限按钮</v-btn>
<br>
<v-btn color="error" @
click="updatePermission">更新按钮所需权限</v-btn>
</div>
</template>
<script>
const USER_PERMISSION=["FUNCTION_USER_ADD","FUNCTION_USER_DEL"];
const USER_ROLE=["ROLE_TEST1","ROLE_TEST2"];
export default {
data() {
return {
permission:['FUNCTION_USER_ADD','FUNCTION_USER_DEL'],
flag:true
};
},
methods:{
updatePermission(){
this.permission=this.flag?["USER_TEST3"]:['FUNCTION_USER_ADD','FUNCTION_USER_DEL'];
this.flag=!this.flag;
}
},
directives: {
permission: {
// 指令的定义
bind: function(el,binding) {
let checkCodes=[];
if(binding.arg==="function"){
checkCodes=USER_PERMISSION;
}else if(binding.arg==="role"){
checkCodes=USER_ROLE;
}else{
checkCodes=USER_PERMISSION.join(USER_ROLE);
}
let access=true;
if(binding.modifiers.all){
for(let need of binding.value){
if(!checkCodes.some(s=>s===need)){
access=false;
break;
}
}
}else{
access=false;
for(let need of binding.value){
if(checkCodes.some(s=>s===need)){
access=true;
break;
}
}
}
if(!access){
el.style.display="none";
}
console.log("bind:"+JSON.stringify(binding),access);
},
update:function(el,binding){
let checkCodes=[];
if(binding.arg==="function"){
checkCodes=USER_PERMISSION;
}else if(binding.arg==="role"){
checkCodes=USER_ROLE;
}else{
checkCodes=USER_PERMISSION.join(USER_ROLE);
}
let access=true;
if(binding.modifiers.all){
for(let need of binding.value){
if(!checkCodes.some(s=>s===need)){
access=false;
break;
}
}
}else{
access=false;
for(let need of binding.value){
if(checkCodes.some(s=>s===need)){
access=true;
break;
}
}
}
if(!access){
el.style.display="none";
}else{
el.style.display="inline-flex";
}
console.log("update:"+JSON.stringify(binding),access);
}
}
}
};
</script>