Vue.js event emitting from child component to (grand)parent component using global eventbus Vue.js event emitting from child component to (grand)parent component using global eventbus vue.js vue.js

Vue.js event emitting from child component to (grand)parent component using global eventbus


The ability to do this goes away with Vue 3. The RFC below mentions the motivation and links to some issues for further help.

https://github.com/vuejs/rfcs/blob/master/active-rfcs/0020-events-api-change.md


I don't think data is the right place for the event bus. I definitely wouldn't use a global mixin for it either.

What I've done in the past is have a simple bus.js file like:

import Vue from 'vue'export default new Vue()

Then, in any component that needs the bus I just

import bus from './bus.js'

Then I normally do this to emit events.

bus.$emit('foo', whatever)

and this to catch them

created () {  bus.$on('foo', this.someMethod)}

I prefer to do it in created since that's the earliest step in the lifecycle you can do this.

Also, this issue on github has some very nice examples: https://github.com/vuejs/vuejs.org/pull/435


You can put the $on listener in the created hook as specified in the docs: https://vuejs.org/v2/guide/components.html#Non-Parent-Child-Communication

You cannot use ready hook in Vue 2.0. ready hook was originally available in Vue 1.x, but now deprecated.


I got the desired effect with a custom event: @newColumn="event"

<init-column @newColumn="event" v-if="newColumn"></init-column>...methods: { event: function(e) { console.log(e) }

So whenever I $emit from the child it does call the event method.

This works well, but for some strange reason the listener $on does not. Maybe I am missing something with the $on method.