1,编写permission.ts文件
在src/utils/permission.ts
import type { Directive } from "vue";
export const permission:Directive={// 在绑定元素的父组件被挂载后调用mounted(el,binding){// el:指令所绑定的元素,可以用来直接操作 DOM// binding:我们通过自定义指令传递的各种参数const {value}=binding;// 这里模拟后端返回来的数据,一般是登录过后存在缓存或者pinia里const permissionButton = ['add', 'edit']if (value && value instanceof Array && value.length > 0) {// 有权限const hasPermission = permissionButton.some((role: string) => {console.log('role',role);return value.includes(role);}); // 没有权限if (!hasPermission) {el.style.display = 'none';}}}
}
2,在main.ts注册
import { createApp, type Directive } from 'vue'
import pinia from './stores'
import App from './App.vue'
import router from './router'// 导入自定义指令
import * as directives from '@/utils/permission'const app = createApp(App)
app.use(pinia)
app.use(router)
app.mount('#app')//挂载自定义指令
Object.keys(directives).forEach(key => {app.directive(key, (directives as { [key: string]: Directive })[key]);});
3,在任意vue文件里使用
<template><div ><button v-permission="['add']">增加</button ><button v-permission="['delete']">删除</button ><button v-permission="['edit']">修改</button ><button v-permission="['query']">查看</button ><button v-permission="['export']">导出</button ></div>
</template>
效果图: