《vue中自定义指令对于按钮权限的控制》

自定义指令对于按钮权限的控制

思路:我们从后端拿到的权限数据利用 directive 中的 el 和 binding 参数进行按钮的显示与隐藏

  • 首先我们模拟一下从后端拿到的数据
1
2
3
4
5
6
7
8
9
<template>
<div>
<h1>利用自定义指令对于按钮权限的控制</h1>

<button v-has="'edit'">编辑</button>
<button v-has="'create'">新建</button>
<button v-has="'delete'">删除</button>
</div>
</template>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<script lang="ts" setup>
import { reactive } from "vue";
interface Permissions {
permissions: Array<string>;
}

const permission = reactive<Permissions>({
permissions: ["edit", "delete"],
});

function setLocalStorage(): void {
localStorage.setItem("vue-permissions", JSON.stringify(permission));
}

setLocalStorage();
</script>

<style>
button {
margin: 10px;
}
</style>
  • 我们跨域新建一个模块 directive/index.ts并挂载到 main.ts 上
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import { App } from "vue";

export default (app: App<Element>) => {
//自定义组件
app.directive("has", (el: HTMLElement, binding) => {
const permissions: Array<string> = JSON.parse(
localStorage.getItem("vue-permissions") || ""
).permissions;
const needPermissions: string = binding.value;
console.log(permissions);
const hasPermissions: boolean = permissions.includes(needPermissions);
if (!hasPermissions) {
setTimeout(() => {
el.parentNode.removeChild(el);
}, 0);
}
});
};
1
2
3
4
5
6
7
import { createApp } from "vue";
import "./style.css";
import App from "./App.vue";
import router from "./router";

import has from "../src/directive/has";
createApp(App).use(router).use(has).mount("#app");