让 Vue3 的自定义指令拥有 TS 类型

481 阅读1分钟

在 Github 关注我

Directive Type

让 Vue 自定义指令拥有 TypeScript 提示与校验

22212.gif

Start Use

directives/index.ts

import type { App, Directive, DirectiveBinding } from 'vue'

const customDirective = (el: Element, binding: DirectiveBinding<string>) => {
  // You code
}

export function setupGlobDirectives(app: App) {
  app.directive('custom', customDirective)
}

main.ts

import { createApp } from 'vue'
import { setupGlobDirectives } from './directives'

const app = createApp(App)
setupGlobDirectives(app)

app.mount('#app')

directive.d.ts

import type { Directive } from 'vue'

declare module 'vue' {
  export interface ComponentCustomProperties {
    vCustom: Directive<Element, string>
  }
}

export {}
  • 鼠标悬浮自定义指令将会获得类型提示
  • 运行 vue-tsc 将校验类型

More

PR 代码示例
VSode 高亮指令插件安装