一.后台维护的数据表存权限信息
二.然后登录以后请求用户基本信息
里面带着permission用户有的权限数组,然后将这个数组setPermissions存进pinia
三.指令函数中判断判定的值在权限数组中有没有,没有就从 Dom 树中移除
function isPerm(el: Element, binding: any) {
const { hasPermission } = usePermission();
const value = binding.value;
if (!value) return;
if (!hasPermission(value)) {
el.parentNode?.removeChild(el);
}
}
const mounted = (el: Element, binding: DirectiveBinding<any>) => {
isPerm(el, binding);
};
const permDirective: Directive = {
mounted, // mounted :在挂载绑定元素的父组件时调用
};
export function setupPermissionDirective(app: App) {
app.directive('perm', permDirective);
}
export default permDirective;
export function usePermission() {
const userStore = useUserStore();
function hasPermission(value: string | string[], def = true): boolean {
// 默认展示
if (!value) {
return def;
}
if (!isArray(value)) {
return userStore.getPermissions?.includes(value);
}
return (
intersection(value, userStore.getPermissions).length === value.length
);
}
return { hasPermission };
}
四.使用