vue3的写法
import { Directive } from "vue";
export const buttonPermissions: Directive<HTMLInputElement, any> = (
el,
binding
) => {
// 这会在 `mounted` 和 `updated` 时都调用
// 获取自定义指令内容
const buttonKey = binding.value;
if (buttonKey) {
const key = checkKey(buttonKey);
if (!key) {
el.remove();
}
}
};
const checkKey = (key: string) => {
// 获取权限数组
const permissionBtnArr = JSON.parse(
sessionStorage.getItem("permissionBtnArr")!
);
console.log(permissionBtnArr);
// 如果传入的元素key不在权限数组里,则不可显示
const permissionData = permissionBtnArr || [];
const index = permissionData.indexOf(key);
return index > -1;
};
import { buttonPermissions } from "@/directive/permission";
const app = createApp(App);
app.directive("permission", buttonPermissions);
vue2的写法
import Vue from "vue";
export const buttonPermissions = Vue.directive("permission", {
inserted(el, binding) {
const buttonKey = binding.value;
console.log(buttonKey);
// 代表某个元素需要通过的权限验证
if (buttonKey) {
const key = checkKey(buttonKey);
// 没有权限
if (!key) {
// 删除按钮
el.remove();
}
} else {
throw new Error("缺少唯一指令");
}
},
});
const checkKey = (key) => {
// 获取权限数组\\
const permissionDataArr = JSON.parse(
sessionStorage.getItem("permissionData")
);
const permissionData = permissionDataArr || [];
// 如果传入的元素key不在权限数组里,则不可显示
const index = permissionData.indexOf(key);
console.log(index);
return index > -1;
};