LoginSignup
10
5

More than 1 year has passed since last update.

【Vue3】親<->子間のコンポーネントメソッド発火方法

Posted at

はじめに

こんにちは。
今回はVue3で親子間のコンポーネント内メソッドの発火方法を紹介していきます。
子から親のメソッドを発火させる方法はご存知の方多いと思いますが親から子のメソッドを直接発火させる方法も紹介していますので参考になれば幸いです。
#注意:Vue3 composition apiの記法で紹介しています。

前提:親と子コンポーネントを作成

まずは親コンポーネントと子コンポーネントを作成していきます。
今回は分かりやすいようシンプルなものにしています。

Child.vue
<template>
  <button
    @click="emitEvent"
  >
    子コンポーネント
  </button>
</template>

<script lang="ts">
import { defineComponent } from '@nuxtjs/composition-api'

export default defineComponent({
  emits: ['childEmit'],
  setup(props, {emit}){
    const emitEvent = () => {
      emit('childEmit')
    }

    const halloFromChild = () => {
      alert('Hello from Child!')
    }

    return {emitEvent, halloFromChild}
  }
})
</script>
Parent.vue
<template>
  <div>
      <button
      @click="halloFromChild"
      >
      親コンポーネント
      </button>
    <Child
      ref="child"
      @childEmit="helloFromParent"
    />
  </div>
</template>

<script lang="ts">
import { defineComponent } from '@nuxtjs/composition-api'
import Child from './Child.vue'

export default defineComponent({
  components: {
    Child
  },
  setup(props, {emit}){
    const child = ref(null)

    const helloFromParent = () => {
      alert('Hello from Parent!')
    }

    const halloFromChild = () => {
      child.value.halloFromChild()
    }

    return {child, helloFromParent, halloFromChild}
  }
})
</script>

子→親のメソッドを発火する

emitを使用します!
子コンポーネントの方で、 emitEvent() というメソッドを叩くと、 childEmit というイベントが親コンポーネントで発火するようになっています。

const emitEvent = () => {
  emit('childEmit')
}

そして、この発行された childEmitイベントを親側で受け取り、実行したいメソッドへと渡してあげます。
今回の例ではhelloFromParentメソッドが実行されます。

<template>
  <div>
      <button
      @click="halloFromChild"
      >
      親コンポーネント
      </button>
    <Child
      ref="child"
      @childEmit="helloFromParent"   この部分
    />
  </div>
</template>

親→子のメソッドを発火する

refのテンプレート参照を使用します!
親コンポーネントのこちらのメソッドに注目してください。

const halloFromChild = () => {
  child.value.halloFromChild()
}

refは指定した対象のDOM要素を引っ張ってこれるもの、と捉えている方も多いと思いますが、refをComponentに指定してあげると、Componentインスタンスがまるっと取得できます。
そして取得したコンポーネント内にあるメソッドを発火させることができます。
これだけで親→子のメソッドを発火させることができます。

Tips : refの型定義

TypeScriptを使用している場合refに型定義をしたいことがあると思います。
refでコンポーネントを参照した場合にどうやって型定義をするか紹介します。

const componentRef = ref<InstanceType<typeof HelloWorld>>()

上記のように記述することで型定義することができます。これで補完や型チェックも効くようになるので活用してみてください!

まとめ

今回はコンポーネント間のメソッド発火方法を紹介しました。少しでも参考になれば幸いです!

10
5
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
5