美文网首页
vue自定义指令封装

vue自定义指令封装

作者: 一颗得道的仙丹 | 来源:发表于2024-03-06 14:36 被阅读0次

    创建一个directives文件夹,在该文件夹下创建一个auth文件夹,然后在此文件夹下面创建一个index.ts文件

    import type { Directive, DirectiveBinding } from "vue";
    
    export const auth: Directive = {
      // 当指令挂载时调用
      mounted(el: HTMLElement, binding: DirectiveBinding) {
        // 获取指令的值
        const { value } = binding;
        console.log(value);
        // 获取本地存储的权限
        const userPermissions = localStorage.getItem("localAuth")
          ? localStorage
              .getItem("localAuth")
              .split(",")
              .map(perm => perm.trim())
          : [];
        // 如果指令有值,则判断本地存储的权限是否包含指令的值,如果不包含则移除该元素
        if (value) {
          !userPermissions.includes(value) && el.parentNode?.removeChild(el);
        } else {
          // 如果指令没有值,则抛出错误
          throw new Error(
            "[Directive: auth]: need auths! Like v-auth=\'pm.work_garbage:workDeleteAction'\""
          );
        }
      }
    };
    

    然后在directives此文件夹下面新增index.tx,该文件作用是当有多个自定义指令时无需重复注册指令

    export * from "./auth";
    

    最后在main.ts中

    // 创建一个应用实例
    const app = createApp(App);
    // 自定义指令
    import * as directives from "@/directives";
    Object.keys(directives).forEach(key => {
      app.directive(key, (directives as { [key: string]: Directive })[key]);
    });
    

    ok结束了

    相关文章

      网友评论

          本文标题:vue自定义指令封装

          本文链接:https://www.haomeiwen.com/subject/thpjzdtx.html