接上一篇自定义指令-按钮防重,这篇记录一下自定义按钮权限控制指令,
全局注册指令见👇
https://blog.csdn.net/lucky_zouzou/article/details/130774462
指令代码
同样的,根据user权限,控制按钮是否展示的指令 v-auth:
import {useUserStore} from '@/stores';
//store中获取用户信息
const userInfo = useUserStore().getUserInfo;
// 判断有无对应权限
function checkAuth(auth:string | string[]) {
const allAuth = userInfo.roles;// 获取user roles
let flag = false;
if(typeof(auth)==='string'){
flag = allAuth.includes(auth);
} else if(auth instanceof Array){
// 若为数组,有其中一个权限即视为有权限(这里根据业务需求来写)
for(const v of auth){
if(allAuth.includes(v)) {
flag = true;
break;
}
}
} else {
throw new Error('sorry 请绑定权限字符串或数组');
}
return flag;
}
export default {
name:'auth', //name即为使用时的指令名称
mounted(el:HTMLElement,binding:any){
//value即为指令传入的值
const {value} = binding;
if(value) {
if(!checkAuth(value)){
el.remove();
}
} else {
throw new Error('sorry 请绑定权限字符串或数组');
}
}
};
使用指令
和使用vue提供的指令一样使用自定义指令:
//具有admin或manager权限的用户会显示此按钮
<button v-auth="['admin','manager']">submit</button>
//可传单个字符串或数组
<button v-auth="'admin'">save</button>