Vue 3でのエミットの仕組みとイベントの送り方

Vue 3でのエミットの仕組みとイベントの送り方

Vue 3ではイベントのエミット機能が改善され、より柔軟で明確なイベント伝播が可能になりました。本記事では、エミットの仕組みと効果的なイベント送信方法について解説します。

エミットとは

エミットは子コンポーネントから親コンポーネントへイベントを送信する仕組みです。

this.$emit('event-name', payload)

emitの基本構文

emitの基本的な使用方法です。

<template>
  <button @click="sendEvent">Click Me</button>
</template>

<script>
export default {
  emits: ['custom-event'],
  methods: {
    sendEvent() {
      this.$emit('custom-event', 'Hello from child')
    }
  }
}
</script>

親コンポーネントでの受け取り

親コンポーネントはv-onを使用してイベントをリッスンします。

<ChildComponent @custom-event="handleEvent" />

methods: {
  handleEvent(message) {
    console.log(message)
  }
}

emitの型定義

Vue 3ではemitイベントに型を指定できます。

emits: {
  'update-title': (value) => typeof value === 'string'
}

emitの検証

emitイベントが正しい形式で送信されているかを検証します。

emits: {
  submit: (payload) => payload !== ''
}

カスタムイベントを複数エミットする

1つのメソッドから複数のイベントを送信できます。

this.$emit('event-a', 'Data A')
this.$emit('event-b', 'Data B')

イベント引数の複数渡し

イベントに複数の引数を渡す方法です。

this.$emit('custom-event', 'value1', 'value2')

v-modelとの連携

v-modelを使用してエミットする例です。

<template>
  <input :value="modelValue" @input="$emit('update:modelValue', $event.target.value)" />
</template>

props: ['modelValue'],
emits: ['update:modelValue']

複数のv-modelイベント

複数のv-modelを同時に扱う方法です。

<template>
  <input :value="title" @input="$emit('update:title', $event.target.value)" />
  <input :value="content" @input="$emit('update:content', $event.target.value)" />
</template>

props: ['title', 'content'],
emits: ['update:title', 'update:content']

イベントの透過的な伝播

子コンポーネントから孫コンポーネントにイベントを透過的に伝播させます。

<ChildComponent v-on="$attrs" />

イベントオプション

イベントの動作をカスタマイズできます。

emits: {
  submit: null,
  close: (payload) => payload === 'confirmed'
}

エミットとリアクティブ性

エミットを使用してリアクティブデータを効率的に管理します。

<template>
  <button @click="$emit('increment')">Add</button>
</template>

emits: ['increment']

まとめ

Vue 3におけるエミットの仕組みは、イベント伝播の柔軟性と保守性を高める重要な要素です。適切に活用することで、コンポーネント間のデータフローがより明確になります。