Skip to content

Commit 1bfa1df

Browse files
committed
Added template refs typing instruction
vuejs/docs@d5c6635
1 parent 5cbfc26 commit 1bfa1df

File tree

1 file changed

+74
-3
lines changed

1 file changed

+74
-3
lines changed

src/guide/typescript-support.md

Lines changed: 74 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -221,10 +221,10 @@ const Component = defineComponent({
221221
// セッターを持つ算出プロパティのでは、ゲッターにアノテーションが必要です
222222
greetingUppercased: {
223223
get(): string {
224-
return this.greeting.toUpperCase();
224+
return this.greeting.toUpperCase()
225225
},
226226
set(newValue: string) {
227-
this.message = newValue.toUpperCase();
227+
this.message = newValue.toUpperCase()
228228
}
229229
}
230230
}
@@ -297,7 +297,7 @@ const Component = defineComponent({
297297
})
298298
```
299299

300-
### emits にアノテーションをつける
300+
### Emit にアノテーションをつける
301301

302302
発行されたイベントのペイロードにアノテーションをつけることができます。また、すべての宣言されていない発行されたイベントは、呼び出されたときに型エラーが発生します:
303303

@@ -372,6 +372,77 @@ year.value = 2020 // OKです!
372372
ジェネリックの型が不明の場合、`ref``Ref<T>` にキャストすることを推奨します。
373373
:::
374374

375+
### テンプレート参照を型定義する
376+
377+
ときどき、子コンポーネントのパブリックメソッドを呼び出すために、テンプレート参照にアノテーションをつける必要があるかもしれません。例えば、 `MyModal` という子コンポーネントにモーダルを開くメソッドがあるとします:
378+
379+
```ts
380+
import { defineComponent, ref } from 'vue'
381+
382+
const MyModal = defineComponent({
383+
setup() {
384+
const isContentShown = ref(false)
385+
const open = () => (isContentShown.value = true)
386+
387+
return {
388+
isContentShown,
389+
open
390+
}
391+
}
392+
})
393+
```
394+
395+
この親コンポーネントからテンプレート参照を介して、このメソッドを呼び出したいです:
396+
397+
```ts
398+
import { defineComponent, ref } from 'vue'
399+
400+
const MyModal = defineComponent({
401+
setup() {
402+
const isContentShown = ref(false)
403+
const open = () => (isContentShown.value = true)
404+
405+
return {
406+
isContentShown,
407+
open
408+
}
409+
}
410+
})
411+
412+
const app = defineComponent({
413+
components: {
414+
MyModal
415+
},
416+
template: `
417+
<button @click="openModal">Open from parent</button>
418+
<my-modal ref="modal" />
419+
`,
420+
setup() {
421+
const modal = ref()
422+
const openModal = () => {
423+
modal.value.open()
424+
}
425+
426+
return { modal, openModal }
427+
}
428+
})
429+
```
430+
431+
この方法でも動作しますが、 `MyModal` とその利用可能なメソッドについての型情報がありません。これを解決するためには、 ref を作成するときに `InstanceType` を使う必要があります:
432+
433+
```ts
434+
setup() {
435+
const modal = ref<InstanceType<typeof MyModal>>()
436+
const openModal = () => {
437+
modal.value?.open()
438+
}
439+
440+
return { modal, openModal }
441+
}
442+
```
443+
444+
[オプショナルチェイニング](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining) や他の方法を使って、 `modal.value` が未定義でないことの確認が必要であることに注意してください。
445+
375446
### `reactive` を型定義する
376447

377448
`reactive` プロパティを型定義する場合、推論を使用できます:

0 commit comments

Comments
 (0)