Vue3 - Implementing a seamless communication channel between two child components

Vue 3 has brought about changes in my component structure, as shown below:

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

What is the best way to create a div that extends beyond the borders of the screen, but still allows only

I am currently working on a React project for a website. I am creating a category bar that should slide only the component in the mobile version, without moving the entire page. Check out the desired design here However, the current appearance is differe ...

Error: Unable to locate module: 'material-ui/styles/colors'

I encountered an issue with the code below, as it failed to compile: import React from 'react'; import { AppBar, Toolbar } from 'material-ui'; import { Typography } from 'material-ui'; import { MuiThemeProvider, createMuiThem ...

Mastering form reset functionality using jquery

When attempting to register, an error is generated if any field is left blank in the form (from PHP). The input fields that have been filled out are retained using Smarty: {if isset($smarty.post.registratie.naam)} value="{$smarty.post.registratie.naam}"{el ...

AngularJS mobile navigation menu toggle not functioning properly with the close feature

I am currently developing a simple Single Page Application (SPA) using an HTML template. The template includes a mobile navigation menu, but I am facing issues with it not closing when navigating through routes in AngularJS. Can anyone provide guidance on ...

What is the rationale behind having getters and mutations accept state, while actions accept context as their first argument in VUEX

Can you explain the reasoning behind getters and mutations accepting state as their first argument, while actions accept context? And how does this reflect the difference between the two, especially considering that context contains all properties of the ...

Styling tables within HTML emails for Gmail and then utilizing PHPMailer to send the emails

I've been racking my brain over this for hours with no luck! Objective: Implementing inline styles for table, td, th, p elements in an HTML email intended for Gmail using PHPMailer. Challenge: Inline styles not being rendered HTML Snippet: <sec ...

Removing an item from a dropdown list in Vue without triggering the change event of the dropdown's event

How can I delete an item by index without triggering an unwanted event? I have a dropdown list with a change event for selecting an item, and when I added a delete button to remove a specific index, the change event also fires before the click event for de ...

Performing an AJAX GET request to the API after a set time interval

The API is constantly updating with live values, so I am attempting to fetch the data every second and display it on the webpage. Although I used a GET request call every N seconds using set_interval(), the values only load once and do not update with eac ...

Encountering 404 errors when reloading routes on an Angular Azure static web app

After deploying my Angular app on Azure static web app, I encountered an error. Whenever I try to redirect to certain routes, it returns a 404 error. However, if I navigate from one route to another within the app, everything works fine. I have attempted t ...

Stop the click event from firing on child elements of a parent element that is currently being dragged

Below is the structure of a UL tag in my code: <ul ondrop="drop(event)" ondragover="allowDrop(event)"> <li class="item" draggable="true" ondragstart="dragStart(event)" ondrag="dragging(event)"> <div class="product-infos"> ...

What is the best way to eliminate a vertical line from the canvas in react-chartjs-2?

Can someone please lend me a hand? I've been working on a project in React JS that involves using react-chartjs-2 to display charts. I'm trying to incorporate a range slider for the chart to manipulate values on the x-axis, as well as two vertic ...

Utilizing NodeJS and Express to enhance the client side for showcasing an uploaded file

My knowledge of nodeJS, AJAX requests, and routing is still in its infancy. After following a tutorial on nodejs and express examples, I managed to get everything working on the server-side. However, I'm facing difficulty displaying the uploaded file ...

"Authentic JavaScript Universal Time Coordinated (UTC) Date

I've been struggling to keep my dates in UTC within my JavaScript application. Surprisingly, the Date's getTimezoneOffset() method does not return a value of 0, which I expected it to do. This seems crucial for accurately converting dates between ...

Having trouble with the clip-path in d3.js liquid fill gauge

Attempting to integrate the d3.js liquid fill gauge into my angular2 webapp has been a challenge. The clippath functionality seems to be malfunctioning, resulting in no wave being generated at all. https://i.stack.imgur.com/3Bmga.png instead of https://i. ...

Updating a data value in Vue3 also updates the corresponding prop

Not sure if this is standard behavior, I'm fairly new to Vue, but it's really frustrating. Hopefully someone here can shed some light on what's going on... Here's my code snippet: props: [ 'asset', //--- asset.price = 50 ...

What is the correct way to properly deploy Nuxt.js in SPA mode on a server?

My current project involves utilizing Nuxt.js in Single Page Application (SPA) mode. However, I am encountering difficulties when trying to deploy it on my Apache server. Has anyone else faced this issue before? I suspect that the problem may be related t ...

Ways to invoke a prop function from the setup method in Vue 3

I encountered the following code: HTML: <p @click="changeForm">Iniciar sesion</p> JS export default { name: "Register", props: { changeForm: Function, }, setup() { //How do I invoke the props change ...

Creating a JSON-based verification system for a login page

First time seeking help on a programming platform, still a beginner in the field. I'm attempting to create a basic bank login page using a JSON file that stores all usernames and passwords. I have written an if statement to check the JSON file for m ...

Error: The value of 'v4' property is not defined and cannot be read

I am encountering an issue with Vue.js: vue.esm.js?efeb:628 [Vue warn]: Error in v-on handler: "TypeError: Cannot read property 'v4' of undefined" found in ---> <AddTodo> at src/components/AddTodo.vue <App> at src/Ap ...

Implementing CodeIgniter's HMVC structure to dynamically update data using AJAX functionality

Recently, I came across an AJAX function in an open-source code that caught my attention. function edit_person(id) { save_method = 'update'; $('#form')[0].reset(); // reset form on modals //Ajax Load data from ajax $.ajax({ ...