Vue3 +TS 封装自定义指令

在main.ts目录同级新建direct.ts文件

import { Directive } from 'vue';
export const permission: Directive = {
  // mounted是指令的一个生命周期
  mounted(el, binding) {
    // value 获取用户使用自定义指令绑定的内容
    const { value } = binding;
    // 获取用户所有的权限按钮 ["order/search","feedback/search"]
    const permissionBtn: any = JSON.parse(sessionStorage.getItem('permission')).data;
    // 判断用户使用自定义指令,是否使用正确了
    if (value && value instanceof Array && value.length > 0) {
      const permissionFunc = value;
      if (!permissionBtn) return false;
      //判断传递进来的按钮权限,用户是否拥有
      //Array.some(), 数组中有一个结果是true返回true,剩下的元素不会再检测
      console.log(permissionBtn, 'permissionBtn');
      const hasPermission = permissionBtn.some((role: any) => {
        return permissionFunc.includes(role);
      });
      // 当用户没有这个按钮权限时,设置隐藏这个按钮
      if (!hasPermission) {
        el.style.display = 'none';
      }
    } else {
      throw new Error("need roles! Like v-permission=\"['admin','editor']\"");
    }
  }
};

权限串类似下图
在这里插入图片描述

在main.ts引入

import { createApp,Directive } from 'vue';
import App from './App.vue';

const app = createApp(App);
Object.keys(directives).forEach(key => {  //Object.keys() 返回一个数组,值是所有可遍历属性的key名
  app.directive(key, (directives as { [key: string ]: Directive })[key])  //key是自定义指令名字;后面应该是自定义指令的值,值类型是string
})
app.mount('#app');
Logo

欢迎加入 MCP 技术社区!与志同道合者携手前行,一同解锁 MCP 技术的无限可能!

更多推荐