Last active
April 19, 2021 05:30
-
-
Save YoshiTheChinchilla/84657ec53c83826245b0466c195b1649 to your computer and use it in GitHub Desktop.
Simple Event Bus pattern in Vue.js and Nuxt.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} | |
} | |
**/ |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
avoid creating listening ($on) in created cycle if you don't want memory leaks in the SSR mode