Vuejs2 - how to create event buses for a hierarchy of individual files

I found the LinusBorg solution here that registers the bus worldwide in any instance of Vue. Is there a way to define this in the component hierarchy instead, so that I can create multiple zones with multiple areas? Basically, if I had several "root" levels with some children, an event bus should be created for the "root" component, and children, and not all Vue instances, should be created for it.

I can’t use simple $emitand $onbecause hierarchy is not limited to simple communication parent-child. Thus, events must be transmitted at several levels.

+4
source share
1 answer

You can create a js file, for example eventBus.js, and simply export the vue instance:

import Vue from 'vue'
const bus = new Vue()
export default bus

then you can import the event bus into a .vue file

import bus from 'path/to/eventBus'

...

bus.$on('foo', ...)

Update my answer from the discussion in the comments:

Since the event name is just a string, you can add a prefix / namespace to the event, for example bus.$emit('domain.foo')or bus.$emit('domain/foo').

If you feel that your application is becoming more complex, just go to vuex.

+5
source

Source: https://habr.com/ru/post/1666702/


All Articles