1.自定义指令

初定登记项目版本
import type { Directive } from 'vue';
import imgNoPermission from '../assets/images/noPermission-bg.png';
const hasPermissionDirective: Directive = {
mounted(el, binding) {
if (binding.value === undefined) return;
const arr = ['测试1'];
const permission = binding.value[1];
const type = binding.value[0] as string; // 类型 按钮 组件
if (!arr.includes(permission) && type === 'button') {
el.style.display = 'none';
el.parentNode.removeChild(el);
console.log(binding);
}
if (!arr.includes(permission) && type === 'module') {
el.style.display = 'flex';
el.style.flexDirection = 'column';
el.style.justifyContent = 'center';
el.style.alignItems = 'center';
el.innerHTML = '';
const img = document.createElement('img');
img.src = imgNoPermission;
img.style.height = '50%';
img.style.maxHeight = '200px';
el.appendChild(img);
const textSpan = document.createElement('div');
textSpan.innerText = '暂无权限,请申请开通';
textSpan.style.color = '#394D73';
textSpan.style.fontSize = '14px';
textSpan.style.paddingTop = '8px';
el.appendChild(textSpan);
}
},
};
export default hasPermissionDirective;

其他项目版本
import type { Directive } from 'vue';
import { useCounterStore } from '@/stores/counter';
import CryptoJS from 'crypto-js';
import imgNoPermission from '@/assets/images/noPermission-bg.png'
const hasPermissionDirective: Directive = {
mounted(el, binding) {
if(binding.value === undefined) return;
const store = useCounterStore()
const userPermissions: any = store.getPermission();
const permission = CryptoJS.MD5(binding.value[1]).toString(CryptoJS.enc.Hex).toLowerCase();
const type = binding.value[0] as string; // 类型 按钮 组件
if(!userPermissions.hasOwnProperty(permission) && type === 'button'){
el.style.display = 'none';
}
if(!userPermissions.hasOwnProperty(permission) && type === 'module'){
el.style.display = 'flex';
el.style.flexDirection = 'column'
el.style.justifyContent = 'center';
el.style.alignItems = 'center';
el.innerHTML = ''
const img = document.createElement('img');
img.src = imgNoPermission
img.style.height = '50%'
img.style.maxHeight = '200px'
el.appendChild(img)
const textSpan = document.createElement('div')
textSpan.innerText = '暂无权限,请申请开通'
textSpan.style.color = '#394D73'
textSpan.style.fontSize = '14px'
textSpan.style.paddingTop = '8px'
el.appendChild(textSpan)
}
}
};

export default hasPermissionDirective;

2.注册全局的自定义指令

import { createApp } from 'vue';
// 全局注册自定义指令
import hasPermissionDirective from './utils/directive';
import App from './App.vue';
const app = createApp(App);
app.directive('auth', hasPermissionDirective);
app.mount('#app');