[Vuejs]-How to implement communication between siblings in vue?

0👍

As you mentioned, there are a bunch of different ways to achieve what you want:

  1. this.$root is arguably pure evil. It breaks Vue principles and makes communication between components difficult to understand and debug.
  2. Event bus is a very controversial pattern, but you can use it (check out Hetal N answer). Also Vue 3 doesn’t have this api, so you’ll have to use some third party library or write your own event emitter.
  3. Store like Pinia generally is a much better solution. It is easy to debug and test.

However the most obvious and direct approach might be to communicate via parent component using props and emits:

// Parent.vue
// template
<Foo @success="isRequestSuccessful = true" />
<Bar :isRequestSuccesfull="isRequestSuccessful" />

// script
const isRequestSuccessful = ref(false)

0👍

Component communication plays major role in Frontend Famrworks like Vue.js.

You can pass data from one component to another component at same level using Event bus and state management (Majorly used Vuex).

export default {
    name: "DemoComponent"
    methods: {
        sendMessage() {
            this.$root.$emit("messafe from Demo component", argument1, argument2)
        }
    }
}

export default {
    name: "TestComponent"
    methods: {
        this.$root.$on("Message from Demo", (argument1, argument2) => {
            console.log("Arg 1" + argument1);
            console.log("Arg 1" + argument2);
        }
    }
}

Avoid using Event Bus for large scal applications instead use Vuex
As $on, $emit such methods have been removed from Vue 3 so it might
throw errors in console.

More details can be found here & here

Leave a comment