通过自定义指令实现菜单显示和权限控制问题。
一、新建一个在src目录下创建包directives,在包中创建一个ts文件。
import { useStore } from "@/store/pinia";function hasRoles(role: any) {const pinaRoles = useStore().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 = useStore().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: any, binding: any) {let type = binding.arg;if (type === "role") {if (!hasRoles(binding.value)) {el.remove();}} else {if (!hasPermissions(binding.value)) {el.remove();}}},
};
二、在main.ts中引入和使用自定义组件。
import { createApp } from "vue";
import App from "@/App.vue";
//引入自定义指令
import auth from "@/directives/auth";const app = createApp(App);//使用自定义指令
app.directive("auth", auth);
//挂载,最后挂载
app.mount("#app");