LoginSignup
12
8

More than 5 years have passed since last update.

Nuxtを使ったコンポーネント間の通信EventBus。知らなかったのでメモ記事

Posted at

前提

環境

  • Nuxt.js(v.2.8.1)

動機

layoutで処理した結果をnuxtタグ(各ページのコンテンツ)に渡したかった。
何か良い方法は無いか探したところ、下記にてとても有用な記事を見つけたので、記事にしました。
[Nuxt.js] EventBusを使ってコンポーネント間で通信する

簡単に使い方を

概略

  • nuxtにはすでに$nuxtというグローバル・Vueオブジェクトがある
  • $nuxtにはどこからもアクセス可能
  • Vueオブジェクトなので、\$emit | \$on | \$offが使える!

今回使った例

発信側:

default.vue
<template lang="pug">
 <header>
  <button @click="onClick">click</button>
 </header>
 <nuxt>
 <footer></footer>
</template>
<script>
 methods: {
  onClick() {
   // グローバルなオブジェクトにエミット
   this.$nuxt.$emit('rootClick')
  }
 }
</script>

受信側:

page.vue
<template lang="pug">
 <div class="content">
  <h1>page</h1>
 </div>
</template>
<script>
 mounted() {
  // グローバルなオブジェクトにハンドラ追加
  this.$nuxt.$on('rootClick', onRootClick)
 },
 beforeDestroy() {
  // ちゃんと後処理
  this.$nuxt.$off('rootClick')
 },
 methods: {
  onRootClick() {
   // header無いのボタンがクリックされました!
  }
 }
</script>

良いと思ったところ

  • 密結合にならないのがやっぱり良いと思いました。emit側は投げっぱなしで良い。
  • これを知るまではstoreをブリッジしたりしてましたが、簡単なやりとりだけのためにstoreを使うのがどうもなーと思っていたので、簡単に書けるのがとても良いと思いました。

詳しくは記事元を是非

[Nuxt.js] EventBusを使ってコンポーネント間で通信する

有用な記事をありがとうございました。

12
8
0

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
12
8