Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue.js 3 this.$root.$on is not a function

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?

like image 787
Čamo Avatar asked Aug 27 '20 18:08

Čamo


People also ask

How do I force render Vue?

The best way to force Vue to re-render a component is to set a :key on the component. When you need the component to be re-rendered, you just change the value of the key and Vue will re-render the component. This is called the Key-Changing Technique, and it's a pretty simple solution, right?

Is Vuex needed in Vue 3?

Let's take a look at why Vuex is is still necessary, even in Vue 3. First, Vuex offers advanced debugging capabilities that Vue 3 features does not. This is a huge bonus for developers, since no one wants to spend all that time debugging! Secondly, Vuex has plugins that extend its capabilities.


2 Answers

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

like image 75
Boussadjra Brahim Avatar answered Oct 16 '22 08:10

Boussadjra Brahim


In a Vue 3 you can use an external library for this: https://v3.vuejs.org/guide/migration/events-api.html#_2-x-syntax

There's no $root space anymore in a Vue 3, so you have to use an event bus pattern with the libraries mentioned in the docs.

like image 36
Alexander Kim Avatar answered Oct 15 '22 03:10

Alexander Kim