[Vuejs]-$emit and $on strange behavior – Vue2

0👍

Consider you have two components A <- B <- C. A is a parent of B and B is of C.

When you use this in component Cthis.$parent.$emit('loader', value), what you are actually doing is – raise an event from component B which can be then used by component A in its template. So the following will work:

<template>
    <!-- A.vue COMPONENT -->
    <div>
        <!-- Component A doesn't know if event raised by B or C -->
        <!-- Component A only sees component B -->
        <B @loader="doSomething($event)">
    </div>
</template>



<script>
    // C.vue COMPONENT
    export default {

        mounted() {
            const compB = this.$parent;

            // It means event is raised on behalf of component B by component C.
            compB.$emit('loader', someValue);
        }
    }
</script>

If you are familiar with Node.js, then every Vue component behaves like an EventEmitter or EventBus. So it can listen to its own events like:

// some-vue-compoennt.vue
<script>
    export default {

        mounted() {

            // LISTEN TO OWN EVENTS
            this.$on('my-own-event', () => console.log('Listening to myself'));

            // After some time
            setTimeout(() => {
                this.$emit('my-own-event', someValue);
            }, 2000);
        }
    }
</script>

Usage – Almost Never:

As far as the usage is concerned, you should not use $parent instance directly. Always adhere to prop and event model for parent-child communication. It is used internally by Vue and only when in certain specialized scenarios like Graphs, Maps related components where grandchildren components need to access data. It created a tight coupling between parent and children. It can also be used when you are programmatically creating orthogonal components like alerts, snackbars, dialogs, etc.

$root is typically used to broadcast events or signal. It is sometimes used to handle or access singleton data. But again consider using Redux or Vuex for this purpose. This solution based on $root doesn’t scale really well

Leave a comment