Typing Custom Directives
Asked Answered
O

3

6

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.
})
Overlie answered 19/2, 2022 at 12:5 Comment(0)
O
9

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
  }
})
Outfall answered 24/6, 2022 at 17:25 Comment(4)
Where did you find what these generic types represent. I can't find them anywhere on the vue docs site.Ringent
In the vue package source code. But it doesn’t really have any effect when using directives.Laurettalaurette
This isn't a correct answer. That types the directive within the defintion, but the question is referring to strong typing in the template.Akbar
While true, that this is not a correct answer to the question, still this was very helpful to me coming here, because it is the first useful thing that comes up when googling for vue custom directives with typescript. It would be nice if the documentation had a typescript section thereCollyrium
S
7

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

Strangles answered 19/2, 2022 at 18:38 Comment(1)
This PR has been merged on April 25th in 4cc9ca8, and should be out in the next Vue versionApace
B
2

You can import DirectiveBinding and also VNode types from Vue

import {  DirectiveBinding , VNode } from 'vue';

const vClickOutside = {

  mounted:(el:HTMLElement, binding:DirectiveBinding, vnode:VNode){
     // do something
  }

}
Brigham answered 13/8 at 16:14 Comment(1)
This answer should now be marked as the correct one. Thank you @morteza_mortezaie. Don't know when this was added but the DirectiveBinding type is now available in v3.5.3.Slap

© 2022 - 2024 — McMap. All rights reserved.