Vue.js global event not working

I have

<component-one></component-one>

<component-two></component-two>
      <component-three></component-three>

A component twocontains a component three.

I am currently in an emitevent to <component-one>be found in <component-three>.

Q <component-one>I fire the event as follows:

this.$bus.$emit('setSecondBanner', finalBanner);

Then in <component-three>I catch him like this:

mounted() {
    this.$bus.$on('setSecondBanner', (banner) => {
        alert('Caught');
        this.banner = banner;
    });
},

But the event never caught!

I define a bus like this (in my core.js):

let eventBus = new Vue();

Object.defineProperties(Vue.prototype, {
    $bus: {
        get: () => { return eventBus; }
    }
});

What could be wrong here? When I check vue-dev-tools, I see that the event was fired!

+4
source share
2 answers

This is a working example for vue1.

Object.defineProperty(Vue.prototype, '$bus', {
	get() {
		return this.$root.bus;
	}
});

Vue.component('third', {
	template: `<div> Third : {{ data }} </div>`,
  props:['data']
});

Vue.component('second', {
	template: `<div>Second component <third :data="data"></third></div>`,
	ready() {
		this.$bus.$on('setSecondBanner', (event) => {
			this.data = event.data;
		});
	},
	data() {
		return {
    	data: 'Defautl value in second'
    }
	}
});

Vue.component('first', {
	template: `<div>{{ data }}</div>`,
	ready() {
		setInterval(() => {
			this.$bus.$emit('setSecondBanner', {
				data: 'Bus sending some data : '+new Date(),
			});
		}, 1000);
	},

	data() {
		return {
    	data: 'Defautl value in first'
    }
	}
});

var bus = new Vue({});
new Vue({
	el: '#app',
	data: {
		bus: bus
	}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/1.0.28/vue.js"></script>
<div id="app">
  <second></second>
  <first></first>
</div>
Run codeHide result
+2
source

Have you tried registering the listener in createdinstead mounted?

In addition, why define a bus using defineProperties, and not just:

Vue.prototype.$bus = new Vue();
+1
source

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


All Articles