LoginSignup
6
5

More than 3 years have passed since last update.

Nuxt.js + Vuetify.jsでグローバルなイベントのやり取りを event bus でやってみる

Last updated at Posted at 2019-05-12

要は Snackbartoasts などのメッセージを $on$emit を使ってグローバルなイベントのやり取りをする感じ。
(これを global event bus というらしい)

npm install

plugins/event-bus.client.js 作成

import Vue from 'vue'

export default (ctx, inject) => {
  inject('bus', new Vue())
}

nuxt.config.js にプラグイン登録

plugins: [
    '~/plugins/event-bus.client.js'
]

Snackbars.vue コンポーネントを作成


<template>
  <v-snackbar
    v-model="isEnabled"
    :color="color"
    :multi-line="true"
    :timeout="timeout"
    top
  >
    {{ text }}
    <v-btn
      dark
      flat
      @click="isEnabled = false"
    >
      <v-icon>
        close
      </v-icon>
    </v-btn>
  </v-snackbar>
</template>

<script>
export default {
  data () {
    return {
      isEnabled: false,
      text: '',
      color: 'success',
      timeout: 5000
    }
  },
  created () {
    this.$bus.$on('snackbar:success', (text) => {
      this.isEnabled = !!text
      this.text = text
    })
    this.$bus.$on('snackbar:error', (text) => {
      this.isEnabled = !!text
      this.text = text
      this.color = 'error'
      this.timeout = 0
    })
  }
}
</script>

layouts/default.vue

<template>
  <v-app>
    <v-content>
      <nuxt />
    </v-content>

    <Snackbars />
  </v-app>
</template>

<script>
import Snackbars from '@/components/common/Snackbars'

export default {
  components: {
    Snackbars
  }
}
</script>

pages/index.vue

<template>
  <v-btn
    @click="successBtn"
  >
    successBtn
  </v-btn>
  <v-btn
    @click="errorBtn"
  >
    errorBtn
  </v-btn>
</template>

<script>
export default {
  methods: {
    successBtn () {
      this.$bus.$emit('snackbar:success', 'success!!!1')
    }
    errorBtn () {
      this.$bus.$emit('snackbar:error', 'error!!!1')
    }
  }
}
</script>

これで successBtnerrorBtn を押すと Snackbars でメッセージが表示されるはず。

参考リンク

6
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
6
5