24

I have a component which triggers this.$root.$emit('some-root-event') like

clickHandler: function() {
    this.$root.$emit("some-root-event", "aaaaaaaaaaaaaaaaaaaaaa");
    console.log('About $root.$emit')
}

Another component inside should catch this event but throws me an error:

this.$root.$on is not a function

The code of the second component looks like

mounted() {
    this.$root.$on("some-root-event", (data) => {
        console.log("About listener catch $root some-root-event"); console.log(data)
    })
}

Can somebody help me please to understand where is the problem?

Boussadjra Brahim
  • 82,684
  • 19
  • 144
  • 164
Čamo
  • 3,863
  • 13
  • 62
  • 114

1 Answers1

18

According to this RFC in Vue.js 3 they removed $on, $once and $off instance methods :

Their motivation :

Vue 1.x implemented the component event system similar to that of AngularJS, with $dispatch and $broadcast where components in a tree can communicate by sending events up and down the tree. In Vue 2, we removed $dispatch and $broadcast in favor of a more state-driven data flow (props down, events up). With Vue 2's API, $emit can be used to trigger event handlers declaratively attached by a parent component (in templates or render functions), but can also be used to trigger handlers attached imperatively via the event emitter API ($on, $off and $once). This is in fact an overload: the full event emitter API isn't a part of the typical inter-component data-flow. They are rarely used, and there are really no strong reason for them to be exposed via component instances. This RFC therefore proposes to remove the $on, $off and $once instance methods

Boussadjra Brahim
  • 82,684
  • 19
  • 144
  • 164
  • 12
    Thank you, could you explain what should be the alternative of `this.$root.$on` / `this.$root.$off` for those who are migrating from Vue2 to Vue3 ? – snoob dogg May 03 '22 at 09:47
  • You can find the migration strategy here: https://v3-migration.vuejs.org/breaking-changes/events-api.html#_2-x-syntax – Ken Jul 26 '22 at 09:24
  • @snoobdogg please check my answer https://stackoverflow.com/questions/63471824/vue-js-3-event-bus/64019074#64019074 – Boussadjra Brahim Jul 26 '22 at 09:46