Vue3 - Implementing a seamless communication channel between two child components

Vue 3 has brought about changes in my component structure, as shown below: https://i.sstatic.net/bgtPB.png

In this setup, ChildA can communicate with ChildB and requires ChildB to update its state accordingly.

In Vue 2, I could send an event from ChildA:

this.$root.$emit('new-message', data)

And then handle it in ChildB:

this.$root.$on('new-message', (data) => {
   this.state = data
})

However, in Vue 3, the methods $on, $once, and $off have been removed. How can I establish this communication in Vue 3?

Answer №1

Utilizing a data attribute, referred to as data in this specific example, allows for the creation of a basic store using reactive. This store can then be imported and utilized by sibling components (Component A and B).

// store.js
import { reactive } from 'vue'

export const store = reactive({
  data: 'New Message',
  setData(something) {
    this.data = something;
  },
})
<!-- ComponentA.vue -->
<script>
import { store } from './store.js'

export default {
  data() {
    return {
      store
    }
  }
}
</script>

<template>From A: {{ store.data }}</template>

Additionally,

<!-- ComponentB.vue -->
<script>
import { store } from './store.js'

export default {
  data() {
    return {
      store
    }
  },
  watch: {
    // To trigger an event upon change:
    'store.data'(newData, oldData) {
      console.log('Data Changed', { newData, oldData });
    }
  },
}
</script>

<template>From B: {{ store.data }}</template>

Updates to the state within the store will automatically propagate to all child components that utilize it. This method provides a simpler alternative to Vue 2's $emit approach, eliminating the need to manually trace events throughout the component hierarchy.

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

Can React tooltips have properties that allow for changing text styles, such as making text bold or unbold?

Seeking assistance on how to change bold text to regular text in react-tooltip. I have already installed npm react-tooltip. Note: The default text appears in bold and I would like it to be normal. ...

Error message encountered in Vue.js application code: Unexpected JavaScript syntax

While attempting to create Vue.js applications, I encountered the following errors: Severity Code Description Project File Line Suppression State Warning TS1005 (JS) ':' expected. VuejsApp JavaScript Content Files C:\Users&bso ...

Exclude a particular row from a table when there is no identifier

My PHP code generates a basic table. <table border="1" id="control> <tbody> <tr>...</tr> <tr>...</tr> <tr>...</tr> //Row #3 <tr>...</tr> <tr>... ...

Displaying empty values in the post via plupload data

I have encountered an issue where a JSON string that I am trying to post is not getting posted, despite being visible in an alert. The strange part is that when I manually create a JSONArray, it gets posted successfully. Below is the code snippet, I would ...

Difficulty in using window.scrollTo within useEffect in reactJS

I'm facing an issue where I am trying to use window.scrollTo on the initial render using the useEffect function. I have stored the vertical offset as an integer in localStorage, but the scrolling is not working and remains at position 0. Problem with ...

Using JQuery to reverse the action of hiding an image

Having some trouble with my Javascript and JQuery skills, so bear with me. I've set up a gallery of images where users can drag and drop them into a designated drop zone. Everything works fine when dragging an image from the gallery to the drop zone a ...

Storing persistent JSON data in a mobile app built with HTML5 involves utilizing the local storage capabilities of the

I am currently working on a mobile app using PhoneGap that is based on HTML technology. When the app is opened for the first time, my goal is to have it download a zip file that includes a JSON file and media files such as images or audio. Once the zip f ...

What could be the reason for my regex succeeding on the client side but failing on the server side

I have implemented a regex pattern to validate usernames, ensuring they only contain English letters, numbers, and underscores. The client-side code works perfectly, preventing any input other than these characters: <input type="text" name ...

Efficient communication across angular modules on a global scale

Currently, I am working on a project that involves Angular2 with multiple modules. One of the main modules is called BaseModule, and in addition to that, there are two extra modules - FirstModule and SecondModule. Each module has its own routing mechanis ...

Is it possible to obtain a user's public URL using the Facebook API in version 2?

In version 1, it is possible to obtain the user's public link by using the following endpoint: /v1.0/me function testAPI() { console.log('Welcome! Fetching your information....'); FB.api('/me', function(response) { ...

Separating the logic of identical schemas and implementing multi-tenancy in Node.js using Mongoose

In the system I am developing, there are two key requirements: Each client needs to be completely isolated from one another Clients can have multiple subsidiaries which they should be able to switch between without needing to re-authenticate, while ensuri ...

What is the best way to upload images in Vue.js without using base64 formatting?

Is there a way to upload an image file without it being base64 encoded? I currently can only achieve base64 format when trying to upload an image. How can I modify the code to allow for regular file uploads? <script> submitBox = new Vue({ el: "#su ...

Looping through elements using JQuery in groups of 2

Let's say I have the following array: Mike Blue Jakob Red Luis Orange and I'm using this JQuery code to loop through it: $.each( arr, function( index, value ){ $( ".div" ).append( "" + value + "" ); } }); Now, I want to modify the ...

Using the Google Chrome console, execute a command on each page within a specified website

While browsing a website, I noticed a bug that required me to manually run a JavaScript function each time I navigated to a different page in order for the site to work smoothly. Is there a way to automate this process upon page load? I am using Google C ...

An error has occurred in the Node.js module export due to an unexpected token

While working on my controller, I initially wrote it like this: module.exports.create_payment = function(){ console.log('create_payment') } However, I encountered an issue with this approach. If I have 10 methods in one controller, I would ...

Are you struggling with the issue of Function components not being able to be given refs? When you try to access the ref, it just fails. Perhaps you should consider using React.forwardRef

I have implemented the "styled" feature from Material UI to add styles to my components. Right now, I am in the process of cleaning up code to remove console errors. Initially, I encountered this warning message: "Warning: React does not recognize the con ...

Is there a way to streamline and optimize this React/Material UI code for faster performance?

There seems to be a lot of repetition in the code that needs to be cleaned up. I'm wondering if the switch statement is necessary. It looks like it requires the muiTheme palette to be passed this way. Also, can these theme constants be placed in a sep ...

Ways to incorporate conditional checks prior to running class methods

Seeking input on handling async data retrieval elegantly. When initializing a class with asynchronous data, I have been following this approach: class SomeClass { // Disabling strictPropertyInitialization private someProperty: SomeType public asy ...

"Users have reported that the Express body-parser feature sometimes results in req.body returning

I have developed a basic Express server that utilizes the body-parser module to access POST parameters. Here is how my application is structured: /index.js: 'use strict'; const express = require('express'); const app = express(); con ...

The images are positioned within the middle of the page, directly beneath the sidebar, rather than at the top. (Vue.Js)

I'm currently working on a Vue.JS photo website and I've hit a roadblock as described in the title. Despite trying various solutions, after spending two hours back and forth with ChatGPT, I've decided to seek help here. Below is the code sn ...