1. 新建 directives/auth.ts
javascript
//导入自定义指令
import auth from '@/directives/auth'// 注册全局自定义指令 v-auth
app.directive('auth', auth);
1.1完整的authDirective.ts
javascript
import { wmsStore } from "@/store/pinia"
// 判断用户是否有某个角色的函数
const hasRoles = (roles: any) => {
const pinaRoles: any = wmsStore().roles;
if (Array.isArray(roles)) {
return roles.some(role => pinaRoles.includes(role));
} else if (typeof roles === 'string') {
return pinaRoles.includes(roles);
} else {
return false
}
}
// 判断用户是否有某个权限的函数,同上
const hasPermissions = (permission: any) => {
return true
}
// 创建自定义指令
export default {
mounted(el: HTMLElement, binding: any) {
const type = binding.arg
if (type === 'role') {
if (!hasRoles(binding.value)) {
el.remove()
}
}
},
};