Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions src/guide/reusability/custom-directives.md
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,10 @@ app.directive('highlight', {
})
```

グローバルカスタムディレクティブは `vue` の `ComponentCustomProperties` インターフェースを拡張することで型付けすることが可能です

詳細: [カスタムグローバルディレクティブの型付け](/guide/typescript/composition-api#typing-global-custom-directives) <sup class="vt-badge ts" />

## カスタムディレクティブを使用するタイミング {#when-to-use}

カスタムディレクティブは DOM を直接操作することでしか必要な機能を実現できない場合にのみ使用してください。
Expand Down
41 changes: 40 additions & 1 deletion src/guide/typescript/composition-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -468,7 +468,8 @@ import { useTemplateRef } from 'vue'
import MyGenericModal from './MyGenericModal.vue'
import type { ComponentExposed } from 'vue-component-type-helpers'

const modal = useTemplateRef<ComponentExposed<typeof MyGenericModal>>('modal')
const modal =
useTemplateRef<ComponentExposed<typeof MyGenericModal>>('modal')

const openModal = () => {
modal.value?.open('newValue')
Expand All @@ -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<HTMLElement, string>

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]
<template>
<p v-highlight="'blue'">This sentence is important!</p>
</template>
```
4 changes: 4 additions & 0 deletions src/guide/typescript/options-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -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) <sup class="vt-badge ts" />