Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typing Custom Directives

I would like to ask a question about Vue's custom directives. As a fan of Typescript, I want to use this feature with type support, yet I could not find any solutions neither on the web nor on the chat.

<button v-clickOutside="myFunc"> Click Outside </button>

When I write my code like this, and add clickOutside directive to Vue, it works without any problem. Yet the clickOutside has no type support, no auto-complete support and it is recognized as any.

To define, I followed the documentation of Vue.

app.directive('clickOutside', (el, binding) => {
  // My code is here.
})
like image 475
Rago Avatar asked Jul 12 '26 02:07

Rago


2 Answers

This is possible using the Directive<T,V> type even though its poorly documented.

import { Directive } from 'vue'

The type takes two type arguments, one for the element type T and one for the binding value V. Use it like this:

app.directive<HTMLElement, string>('clickOutside', {
  mounted (el, { value }) {
    // el:  HTMLElement
    // value: string
  }
})
like image 194
Jonas Mærsk Avatar answered Jul 13 '26 16:07

Jonas Mærsk


Typing custom global directives is currently not yet supported, but there's an open Pull Request to add support for it.

like image 45
tony19 Avatar answered Jul 13 '26 17:07

tony19



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!