Skip to content

Instantly share code, notes, and snippets.

@YoshiTheChinchilla
Last active April 19, 2021 05:30
Show Gist options
  • Save YoshiTheChinchilla/84657ec53c83826245b0466c195b1649 to your computer and use it in GitHub Desktop.
Save YoshiTheChinchilla/84657ec53c83826245b0466c195b1649 to your computer and use it in GitHub Desktop.
Simple Event Bus pattern in Vue.js and Nuxt.js
<template>
</template>
<script>
// Import the Event Bus of Vue instance
import { EventBus } from './event-bus.js'
export default {
created() {
(this.$nuxt || EventBus || this.$EventBus).$on('open-alert', this.openAlert)
},
beforeDestroy() {
(this.$nuxt || EventBus || this.$EventBus).$off('open-alert')
},
methods: {
openAlert: ({message}) => alert(`Click event emitted!\n${message}`)
}
}
</script>
<template>
<div @click="emitAlertEvent('Just clicked!')">Click me!</div>
</template>
<script>
// Import the Event Bus of Vue instance
import { EventBus } from './event-bus.js'
export default {
methods: {
emitAlertEvent(message) {
(this.$nuxt || EventBus || this.$EventBus).$emit('open-alert', {message})
}
}
}
</script>
import Vue from 'vue'
export const EventBus = new Vue()
// Use Prototype Pattern
/**
Object.defineProperties(Vue.prototype, {
$eventBus: {
get: function () {
return EventBus;
}
}
}
export default {
created() {
this.$EventBus.$on('open-alert', this.openAlert)
}
}
**/
<template>
<base-button></base-button>
<base-alert></base-alert>
</template>
<script>
import BaseButton from './BaseButton.vue'
import BaseAlert from './BaseAlert.vue'
export default {
components: {
BaseButton,
BaseAlert
}
}
</script>
@mercs600
Copy link

avoid creating listening ($on) in created cycle if you don't want memory leaks in the SSR mode

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment