在vue3+ts中封装自定义指令

发布时间 2023-10-17 10:45:53作者: SeriousSnow

src/main.js

// 自定义指令
import * as directives from "@/directives";
Object.keys(directives).forEach(key => {
  app.directive(key, (directives as { [key: string]: Directive })[key]);
});

这里注意类型“Directive”,需要从vue引入

import type { Directive, ... } from "vue";

“...”为你可以需要引入的其他类型


将自定义指令的逻辑封装在src下的directives文件夹下
假设要自定义四个指令如下,在
src/directives/index.ts

export * from "./auth";
export * from "./copy";
export * from "./longpress";
export * from "./optimize";

Object.keys(directives)能够返回键的数组,在这里返回的是["auth", "copy", ..., ...]


拿auth举例,在此目录(当然也可以不额外创建auth文件夹,直接和上面index.ts在同一个目录下)

src/directives/auth/index.ts

//此处代码为auth指令的业务逻辑,不需要过度考虑
import { hasAuth } from "@/router/utils";
import type { Directive, DirectiveBinding } from "vue";

export const auth: Directive = {
  mounted(el: HTMLElement, binding: DirectiveBinding) {
    const { value } = binding;
    if (value) {
      !hasAuth(value) && el.parentNode?.removeChild(el);
    } else {
      throw new Error(
        "[Directive: auth]: need auths! Like v-auth=\"['btn.add','btn.edit']\""
      );
    }
  }
};

然后便可以使用v-auth指令

其他指令类似