1.新建directives auth.ts
2.完整的auth.ts
import { wmsStore } from "@/store/pinia";
//判断是否有某个角色的函数
function hasRoles(role: any) {
const pinaRoles = wmsStore().roles;
if (typeof role === 'string') {
return pinaRoles.includes(role)
} else if (Array.isArray(role)) {
return pinaRoles.some(item => role.includes(item))
} else {
return false
}
}
//判断是否有某个权限的角色
function hasPermissions(permissions: any) {
const pinaPermissions = wmsStore().permissions;
if (typeof permissions === 'string') {
return pinaPermissions.includes(permissions)
} else if (Array.isArray(permissions)) {
return pinaPermissions.some(item => permissions.includes(item))
} else {
return false
}
}
//创建自定义指令
export default {
mounted(el: HTMLElement, binding: any) {
const type = binding.arg;
if (type === "role") {
if (!hasRoles(binding.value)) {
el.remove();
}
}else{
if (!hasPermissions(binding.value)) {
el.remove();
}
}
},
};
3.在main.ts中引入使用
4.在其他组件中使用
4.1菜单中
4.2其他组件中