Help us understand the problem. What is going on with this article?

Nuxt(Vue) + TypeScriptでの$refsの参照エラー

概要

子コンポーネントで定義したメソッドを親コンポーネントから直接呼び出したい!
そうだ$refsを使おう!

Property '子コンポーネントのメソッドないしはプロパティ名' does not exist on type 'Element | Element[] | Vue | Vue[]'.
Property '子コンポーネントのメソッドないしはプロパティ名' does not exist on type 'Element'.

そんなプロパティないって言われてるやんけぇ_:(´ཀ`」 ∠):

解決策

<template>
    <children-component ref="children"></children-component>
</template>

<script lang="ts">
import { Component, Vue } from 'nuxt-property-decorator'
import ChildrenComponent from '@/components/organisms/ChildrenComponent.vue'

@Component({
  name: 'ParentComponent',
  components: {
    ChildrenComponent,
  }
})
export default class ParentComponent extends Vue {
    $refs!: {
        children: ChildrenComponent
    }

    // ChildrenComponentにあるfugaメソッドを直接ParentComponentで呼びたい場合
    private hoge(): void {
        this.$refs.children.fuga()
    }
}

</script>

詳細

importした子のコンポーネントを型として呼び出せば、その子のコンポーネントにあるpublicのプロパティやメソッドは直接呼び出せる!

<script lang="ts">
import { Component, Vue } from 'nuxt-property-decorator'

@Component({
  name: 'ChildrenComponent'
})
export default class ChildrenComponent extends Vue {
    // アクセスできない
    private murimeProperty: string
    // アクセスできる
    public fugaProperty: string

    // できない
    private murimeMethod(): void {}
    // できる
    public fuga(): void {}
}
</script>

余談

ちゃんと型定義すると補完で出てくるの気持ちよすですよねー
今回の場合はVueクラスの$refsをオーバーライドしてるんかな・・
もっとTypeScriptの深淵にゆきたい今日この頃

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした