What are some strategies for establishing communication between sibling components in Vue?

Currently, my Vue app has a structure that includes a "blackout" component for displaying modals and a router-view for various sub-menus. These components are siblings at the same level.


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

Within the dynamically loaded component in "blackout" (using the :is directive), there is a save button used to send data via a POST method. After clicking this save button, I need to refresh the data in the child component of the "router-view". How can I notify the sibling component that the modal component has made a post request and was closed?

After conducting some research, I came across a few potential solutions: using an event bus (considered an antipattern), watching the store state (storing the modal's state in Pinia), or communicating through this.$root (only available in Vue 2).

Answer №1

There are multiple methods you can explore to achieve your desired outcome:

  1. Using this.$root is not recommended as it goes against Vue principles and can make component communication confusing and hard to debug.
  2. The event bus pattern is another option, although it is considered controversial. Keep in mind that Vue 3 does not natively support this, so you may need to utilize a third-party library or create your own event emitter.
  3. A store like Pinia is often seen as a more efficient solution. It offers easier debugging and testing capabilities.

An alternative approach is to communicate through the parent component using props and emits:

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

// script
const isRequestSuccessful = ref(false)

Answer №2

Effective communication between components is crucial in frontend frameworks such as Vue.js.

Data can be transmitted from one component to another at the same level by utilizing tools like Event bus and state management systems (particularly popular is Vuex).

export default {
    name: "DemoComponent"
    methods: {
        sendMessage() {
            this.$root.$emit("message 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);
        }
    }
}

In large-scale applications, it is recommended to avoid using Event Bus and opt for Vuex instead. With Vue 3, methods like $on and $emit have been deprecated, potentially leading to console errors.

For further information, refer to articles located here and here

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a way to retrieve the name of a JSON or obtain the file path using NodeJS Express Router?

I've been experimenting with adding a named routers feature to the Express router for my NodeJS project. I managed to implement it successfully, but there's one thing I'm stuck on... the path. Specifically, when I have a route setup like thi ...

Vue.js - The dissonance between data model and displayed output

Below is a simplified example of my issue: <html> <head> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.1/jquery.min.js"></script> <script src="https://unpkg.com/vue/dist/vue.js"></script> ...

What could be causing npm to fail to launch?

Whenever I execute node app.js, my server functions perfectly. However, when attempting to utilize nodemon for running the server, it fails to start. The error displayed by npm start is as follows: npm ERR! code ELIFECYCLE npm ERR! errno 9009 npm ERR! < ...

Creating Component Variants for Google Optimize A/B testing in Next.js

I've been attempting to create a component variant in Google Optimize beyond just text or color changes, but I haven't found a suitable method to do so yet. I'm looking for guidance on how to integrate/configure Optimize with my code in orde ...

Setting the current date of a jQuery datepicker to the value of an input tag

I am looking to assign a value to an input tag that has a datepicker attached to it. Upon initialization of the datepicker, I want to set this value. Below is a hypothetical example of what I am trying to achieve: HTML: <input id="test" value="">&l ...

cPanel is incompatible with node version 12.16.0

I am facing a dilemma regarding hosting my node API, which was built using node version 12.16.0, on cPanel. The available version for node in cPanel is 12.9.0 (Most recent). How should I proceed? Is the node version really a critical factor in this case? ...

jQuery scripts were not loaded, resulting in an uncaught type error

Hey there! I am currently using jQuery Tablesorter to handle pagination on my website, but it seems to be throwing an error in the browser console. The specific error message reads: Uncaught TypeError: undefined is not a function viewTags:24 (anonymous fu ...

Using Modal Functions in AngularJS Controller

I have been working on a project that utilizes the ui.bootstrap. As per the instructions from the tutorial I followed, my setup looks something like this: 'use strict'; angular.module('academiaUnitateApp') .controller('EntryCtr ...

Real-time Data Stream and Navigation Bar Location

Utilizing the EventSource API, I am pulling data from a MySQL database and showcasing it on a website. Everything is running smoothly as planned, but my goal is to exhibit the data in a fixed height div, with the scrollbar constantly positioned at the bott ...

Error: Attempting to access the 'client' property of an undefined object

I'm currently working on a basic discord.js bot. Below is the code snippet that generates an embed: const Discord = require('discord.js') require('dotenv/config') const bot = new Discord.Client(); const token = process.env.TOKEN ...

Button react-native press following textInput within scroll view aware of keyboard movements

I'm currently facing an issue where I have a TextInput and a button nested inside a KeyboardAwareScrollView. The goal is for the user to input some text and then tap the button created using TouchableOpacity, which should send the inputted text forwar ...

Checking whether a node stream operates in objectMode

When working with a node js stream object, how can I ascertain if it is an object stream in objectMode? For example, suppose I have a readable stream instance: const myReadableStream = new ReadableStreamImplementation({ options: { objectMode : true } ...

Vue alert - Cannot access indexOf property of a value that is undefined

After browsing through numerous similar issues on StackOverflow, none seem to address the specific problem I encountered... I have been smoothly working on a Vue JS project + Laravel until I suddenly encountered an error that seems unsolvable (even though ...

Prevent WordPress themes from running in order to integrate a personalized Vue.js front-end application

I'm currently working on a basic website that will utilize vuejs as the front-end framework and wordpress for generating dynamic content. To achieve this, I've placed wordpress inside the public directory of my vue project in a folder named app. ...

What is the best way to enable autocomplete in AngularJS?

I am working with an object that contains both a name and an ID. I want to implement autocomplete functionality based on the name property. Below is the code snippet that I have tried: //Js file var app=angular.module("myapp",[]); app.controller("controll ...

Troubleshooting issues with sending data from Node.js to MongoDB

I recently started learning nodeJS and I'm facing an issue with sending data from a register form to mongodb. It seems like I made a mistake while using the post method, as I am unable to see the data on postman. const express = require('express& ...

Navigating the issue of updateMany not functioning properly in mongoose and nodejs

I need assistance with updating the author name of a post whenever the user updates their profile name. My code is as follows: router('/:id', async (req, res) { if (req.body._id == req.params.id) { try { const user = await ...

In the Sandbox, element.firstChild functions properly, but it does not work in the IDE

Encountered an issue that has me puzzled. To give you some context, I attempted to create a native draggable slider using React and positioned it in the center of the screen, specifically within my Codesandbox file. The code snippet I utilized is as follow ...

How to implement an instance method within a Typescript class for a Node.js application

I am encountering an issue with a callback function in my Typescript project. The problem arises when I try to implement the same functionality in a Node project using Typescript. It seems that when referencing 'this' in Node, it no longer points ...

The operation of executing `mongodb - find()` does not exist as a function

I am having trouble printing all documents from the "members" collection. I attempted to use the find() function, but encountered an error stating that find() is not a function. Here is a snippet from member_model.js located in the models/admin folder: v ...