Home > Software design >  difference between using this.$emit and this.$root.$emit
difference between using this.$emit and this.$root.$emit

Time:11-10

is there a difference between using $emit directly and $root.$emit ? => this.$emit('default-choice', this.choice); & this.$root.$emit('default-choice', this.choice);

`this.$emit('default-choice', this.choice);`

`this.$root.$emit('default-choice', this.choice);

CodePudding user response:

I think you don't need to use root emit for any case. It's really good to have emit we can emit to the parent component but when it comes to root emit if you ever think "I need to use root emit" then think again and try to use something else (ex: vuex).

and also in Vue.js 3 they removed $on, $once and $off instance methods

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

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

CodePudding user response:

If you need something global, you'll use a store.

An $emit is meant to be used from parent to child and is the probably the one you'll be using 99% of your time.

On top of that, the documentation doesn't really approach the $root.$emit last time I checked. Hence that one could be ignored.

Keep things simple, it will be easier to debug thanks to Vue devtools.

  • Related