diff --git a/src/guide/reusability/custom-directives.md b/src/guide/reusability/custom-directives.md index bee9494e..2a73269c 100644 --- a/src/guide/reusability/custom-directives.md +++ b/src/guide/reusability/custom-directives.md @@ -110,6 +110,10 @@ app.directive('highlight', { }) ``` +グローバルカスタムディレクティブは `vue` の `ComponentCustomProperties` インターフェースを拡張することで型付けすることが可能です + +詳細: [カスタムグローバルディレクティブの型付け](/guide/typescript/composition-api#typing-global-custom-directives) + ## カスタムディレクティブを使用するタイミング {#when-to-use} カスタムディレクティブは DOM を直接操作することでしか必要な機能を実現できない場合にのみ使用してください。 diff --git a/src/guide/typescript/composition-api.md b/src/guide/typescript/composition-api.md index 849fbac3..852425b6 100644 --- a/src/guide/typescript/composition-api.md +++ b/src/guide/typescript/composition-api.md @@ -468,7 +468,8 @@ import { useTemplateRef } from 'vue' import MyGenericModal from './MyGenericModal.vue' import type { ComponentExposed } from 'vue-component-type-helpers' -const modal = useTemplateRef>('modal') +const modal = + useTemplateRef>('modal') const openModal = () => { modal.value?.open('newValue') @@ -477,3 +478,41 @@ const openModal = () => { ``` なお、`@vue/language-tools` 2.1 以降では、静的テンプレート参照の型は自動的に推論されるので、上記はエッジケースでのみ必要となります。 + +## カスタムグローバルディレクティブの型付け {#typing-global-custom-directives} + +`app.directive()` で宣言されたグローバルカスタムディレクティブで型ヒントと型チェックを取得するために、`ComponentCustomProperties` を拡張することができます + +```ts [src/directives/highlight.ts] +import type { Directive } from 'vue' + +export type HighlightDirective = Directive + +declare module 'vue' { + export interface ComponentCustomProperties { + // v をプレフィックスとして付ける(v-highlight) + vHighlight: HighlightDirective + } +} + +export default { + mounted: (el, binding) => { + el.style.backgroundColor = binding.value + } +} satisfies HighlightDirective +``` + +```ts [main.ts] +import highlight from './directives/highlight' +// ...その他のコード +const app = createApp(App) +app.directive('highlight', highlight) +``` + +コンポーネントでの使用方法 + +```vue [App.vue] + +``` diff --git a/src/guide/typescript/options-api.md b/src/guide/typescript/options-api.md index d63179ed..6c24cb2c 100644 --- a/src/guide/typescript/options-api.md +++ b/src/guide/typescript/options-api.md @@ -291,3 +291,7 @@ declare module 'vue' { 参照: - [コンポーネントの型拡張の TypeScript の単体テスト](https://github.com/vuejs/core/blob/main/packages-private/dts-test/componentTypeExtensions.test-d.tsx) + +## カスタムグローバルディレクティブの型付け {#typing-global-custom-directives} + +参照: [カスタムグローバルディレクティブの型付け](/guide/typescript/composition-api#typing-global-custom-directives)

AltStyle によって変換されたページ (->オリジナル) /