親子関係とかがないコンポーネント間でデータの受け渡しをやろうとした時に「EventBus
」という通信の方法があるのを見つけたので実装方法を説明していきたいと思います。
前提条件
- vue:2.6.14
- nuxt:2.15.8
こちらから今回のソースコードを確認できます。
実装のポイント
$emit,$on,$off
を使用してEventBus
を実装します。
受信側ではmounted
のタイミングでイベントハンドラを追加し、beforeDestroy
で後処理の実装(追加したイベントハンドラをoff
にする)が必要になります。
実装サンプル
送信側と受信側のコンポーネントを作成し、pages
でそれぞれのコンポーネントを呼び出しています。
送信側(EventBusSend.vue)
<template>
<v-btn tile @click='sendMessage'>送信</v-btn>
</template>
<script>
export default {
name: 'EventBusSend',
methods: {
sendMessage() {
this.$nuxt.$emit('SEND_MESSAGE', 'メッセージを送信しました。')
},
},
}
</script>
受信側(EventBusReceive.vue)
<template>
<span>送信された値:{{ message }}</span>
</template>
<script>
export default {
name: 'EventBusReceive',
data() {
return {
message: '',
}
},
mounted() {
this.$nuxt.$on('SEND_MESSAGE', (result) => {
this.message = result
})
},
beforeDestroy() {
this.$nuxt.$off('SEND_MESSAGE')
},
}
</script>
pages(EventBus.vue)
<template>
<v-card>
<v-card-title>EventBusサンプル</v-card-title>
<v-card-text>
<event-bus-receive />
</v-card-text>
<v-card-actions>
<event-bus-send />
</v-card-actions>
</v-card>
</template>
<script>
import EventBusReceive from '~/components/EventBusReceive'
import EventBusSend from '~/components/EventBusSend'
export default {
name: 'EventBus',
components: { EventBusSend, EventBusReceive }
}
</script>
動作確認
「送信」ボタンをクリックすると...。
メッセージが表示されました!!
最後に
親子関係がないコンポーネント間でデータのやりとりを行うことができました。これでコンポーネントを分割して疎結合にしてもコンポーネント間で問題なくデータのやり取りをすることができます。
こちらから今回のソースコードを確認できます。