this.$emit vs. this.$root.$emit, best practice in vuejs
Asked Answered
A

1

6

I have vue2 components that are added and removed with v-if. In some cases I communicate between them with $emit from the sender, and $on in the receiver.

I've been using this.$root.$emit to broadcast custom events and this.$root.$on to handle the events. I've discovered using this.$root.$on requires this.$root.$off (from beforeDestroy), otherwise the removed component may attempt to handle it, and bad things happen.

I have two questions:

  1. What's the difference between this.$root.$emit and this.$emit?
  2. If I use this.$on, do I also have to pair it with this.$off? Or will the handler automatically go "off" when the component is removed?
Allahabad answered 27/6, 2021 at 0:9 Comment(3)
Just as a heads up, usually root emits are never a good idea, unless some particular case. To back this up in fact vue3 removed its support. I'm not even sure why you would need $on, as even those are pretty much edge cases.Safir
@CristianoSoleti Really? How is the use of $on edge case? I use them a lot to react on changes in other vue components. Did I miss something? How else can you communicate between components?Diplosis
Using the listeners as vue suggests. vuejs.org/v2/guide/…Safir
D
8
  1. What's the difference between this.$root.$emit and this.$emit?

this.$root gets the root component instance (usually App.vue), so this.$root.emit emits an event from the root component.

this.$emit simply emits an event from the current component.

  1. If I use this.$on, do I also have to pair it with this.$off? Or will the handler automatically go "off" when the component is removed?

this.$off is not needed. Yes, the handler will automatically be removed when the component is destroyed.

Danaedanaher answered 27/6, 2021 at 1:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.