skip to Main Content

I got vue app with following structure:
"blackout" component for poping up modals and router-view for all sub-menues.
Those are sibling (located at one level).


<blackout v-if="this.popup.currentPopup"></blackout>
     ....
<router-view class="folder">
  ...child-component with get request displaying data
</router-view>

There is a saving button for sending data with post method in dynamic loaded component at "blackout"(:is directive). After click save button I need to re-fetch data at "router-view"’s child component.
My question is how to notify sibling component that sibling-modal have made a post request and was closed.

After some researches I find out some: event-bus (antipattern), watching store state (keep modal’s state in pinia), communicate through this.$root (available only in vue2).

2

Answers


  1. 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

    Login or Signup to reply.
  2. 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)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search