The challenge of maintaining consistency in Vue 3 when it comes to communication between

Context

In my Vue 3 application, there is a HomeView component that contains the following template structure:

  <InputsComponent></InputsComponent>
  <CheckboxesComponent></CheckboxesComponent>
  <Toolbar></Toolbar>

The InputsComponent displays text inputs, while the CheckboxesComponent displays checkboxes.

The Toolbar component includes buttons, including a "reset" button.

This question focuses on how to facilitate communication between sibling components.

Objective

When a user fills in inputs or selects checkboxes, pressing the reset button in the Toolbar should reset both the InputsComponent and CheckboxesComponent, allowing users to fill them again and reset as needed. The logic of resetting within each component is not important; what matters is coordinating communication among the three components.

Prior Knowledge

I am avoiding using EventBus in Vue 3 as it is discouraged.

Attempted Solution

I attempted utilizing the parent component as a bridge for communication:

Toolbar.vue

<button @click="$emit('reset')"> Reset </button>

HomeView.vue

<script setup>
const state = reactive({
  resetRequested: false
})

function requestReset() {
  state.resetRequested = true;
}

</script>

<template>
  <main>
    <InputsComponent :reset-requested="state.resetRequested"></InputsComponent>
    <CheckboxesComponent :reset-requested="state.resetRequested"></CheckboxesComponent>
    <Toolbar @reset="requestReset()"></Toolbar>
  </main>
</template>

InputsComponent.vue

<script setup>
const props = defineProps({
    resetRequested: boolean,
})

watch(
  () => props.resetRequested,
  (resetRequested) => {
    if (resetRequested == true)
        //logic to reset the inputs
  }
)

</script>

<template>
  <main>
    <input type="text" /> //and other input elements
  </main>
</template>

CheckboxesComponent functions similarly but with checkboxes.

This approach works initially, but I face issues when trying to hit the reset button multiple times since the prop remains set to true. I also tried having InputsComponent emit an event to the parent to change the prop value to false, but this caused an overall breakdown in behavior.

Challenge

Is there a more efficient way to handle this communication rather than constant back-and-forth interactions between children and their parent? This complexity seems unnecessary.

My current process involves:

  • Toolbar sending an event to HomeView
  • HomeView updating a prop in CheckboxesComponent and InputsComponent
  • CheckboxesComponent and InputsComponent responding to the prop update and performing their actions, then sending an event back to HomeView
  • HomeView resetting the props in CheckboxesComponent and InputsComponent to start the cycle anew

This method feels convoluted and cumbersome.

Additionally, ensuring that both Components reset simultaneously or giving the parent a separate state variable for each child adds further complications.

What am I overlooking? Is there a better approach I could take instead of persisting with this intricate process?

Answer №1

To facilitate communication between sibling components, it is recommended to create a central store such as:

stores/form.js

export const form = ref({
    field1: '',
    field2: '',
    resetFields() {
        this.field1= '';
        this.field2= '';
    }
});

ToolsBar.vue

import {form} from "../stores/form.js"

// ...

<button @click="form.resetFields()"> Reset </button>

InputsComponent.vue

<script setup>
import {form} from "../stores/form.js"

</script>

<template>
  <main>
    <input type="text" v-model="form.field1" /> 
  </main>
</template>

For larger applications, consider using state management libraries like pinia for better organization.

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

Error encountered in Google's Structured Data Testing Tool

<script type="application/ld+json"> {"@context" : "http://schema.org", "@type" : "LocalBusiness", "name" : "mywebsite.com", "description": "Lorem ipsum dolor sit amet", "image" : "http://mywebsite.com/image.jpg", "telephone" : "987654321", ...

Sending a POST request to an API with Angular and passing an object as the payload

I'm currently working on adding a feature to my app where I can take the products from an order and send them to the cart, essentially replicating the entire order. While I have successfully retrieved the order, I am facing difficulty in sending it b ...

Looking to iterate through MongoDB using a promise and a forEach loop? I'm aiming to populate an array

I've been struggling to iterate through elements in my MongoDB database and save the values to an array. Despite putting in hours of effort, I can't seem to get it done. Here's the code snippet: //shopController.js const Product = require ...

Reloading the table columns in a JSP page with a click of the refresh button on every row using AJAX and JavaScript

Hey there! I have a JSP page with a table where data is displayed by iterating through a list from the action class. Each row in the table has a refresh button at row level. Here is a snippet of the JSP: <script type="text/javascript"> functi ...

leveraging axios to work with pagination data from Laravel array

Hey everyone, I could really use some help here. I'm feeling pretty stuck and frustrated because I can't seem to figure out what's wrong with my code. Let me provide more details. The snippet above is supposed to enable pagination from a Lar ...

The addition of special characters to strings in TypeScript through JavaScript is not functioning as expected

I need assistance on conditionally appending a string based on values from captured DOM elements. When the value is empty, I want to include the special character "¬". However, when I try adding it, I get instead because the special character is not reco ...

Encountering error TS2307: Module 'redux' not found when trying to implement redux in Angular 7

Currently, I am diving into the world of Redux and attempting to integrate it into my Angular 7 project using ng2-redux. However, upon visiting the npm page, I discovered that the recommended approach was to install it with npm install @angular-redux/store ...

Why do I keep encountering invalid errors with Vuelidate and TailwindCSS?

I am struggling to comprehend why I keep encountering validation errors. The logic seems fine, so it must be something wrong with my :class bindings. Even though I know I will feel foolish once I figure it out, I have gone through numerous tutorials and st ...

"Can you explain the method by which reveal.js adjusts the size of

I have been exploring the resizing behavior of elements in reveal.js and trying to understand how they dynamically adjust. If you resize the page height, you can observe that the elements shrink up to a certain extent along with the page. However, when in ...

Unit test failure attributed to misconfigured ECMAScript module setup

I am currently using Vue 3 along with Jest for testing purposes. I have created a simple code snippet to test, which is displayed below. Following some suggestions on Stack Overflow, I made some modifications to the babel.config.js and package.json files a ...

Transforming JSON data from a Javascript object into Ruby

When I send an object from Javascript to a Sinatra POST route, I use the 'stringify' method to convert the JS object to JSON. The JSON that is being sent looks like this (based on the Chrome developer tools): {"a":1,"b":2,"c":"3"}: In my Sinatr ...

Attach the element to the bottom of the viewport without obstructing the rest of the page

My challenge is to create a button that sticks to the bottom of the viewport and is wider than its parent element. This image illustrates what I am trying to achieve: https://i.stack.imgur.com/rJVvJ.png The issue arises when the viewport height is shorte ...

I am requesting for the average to be adjusted based on the user's choice between Hindi or English percentage scale

Currently, the average is being calculated in the HTML code. When a user input is changed, the average breaks. What can be done to update the average for each individual person? Controller var app = angular.module('myApp', []); app.controller( ...

The error message "VueRouter does not have a property named 'history'" is common in Vue with TypeScript

In my typescript vue application, I encountered an error within a component while trying to access a parameter passed into the route. Here is the relevant code snippet: properties = getModule(PropertiesModule, this.$store); mounted() { id = this.$router. ...

"Utilize Vue i18n to properly display currency amounts in USD

Whenever I present my currency as USD, it always shows up like this: USD$500.00. I am attempting to eliminate the USD prefix from the beginning. Below is my numberFormats configuration: numberFormats: { 'en': { currency: { ...

JavaScript - Error encountered when accessing information from elements in the DOM

Just started learning javascript and encountering a problem that I can't seem to solve. I'm attempting to assign the className of a <div> element to a variable, but I keep receiving this error message: scripts.js:30 Uncaught TypeError: Can ...

Unlocking the res property in index.js from an HTML script tag: A step-by-step guide

Can anyone help me with the access variable issue I am facing? I have two files, index.js and page.ejs. These files require me to create a timer linked with datetimes stored on my local server. //index.js.. router.get('/mieiNoleggi', functio ...

Error occurs when attempting to access window.google in Next.js due to a TypeError

I've been working on integrating the Google Sign In feature into my Next app. Here's how I approached it. In _document.js import React from 'react'; import Document, {Html, Head, Main, NextScript } from 'next/document'; expo ...

What is the purpose of storing JSON data as a string within another JSON object?

Screenshot of developer tools While exploring the local storage on my visit to YouTube, I came across some very peculiar-looking JSON data. { creation: 1638112285935, data: "{\"quality\":1080,\"previousQuality&bs ...

The array is producing accurate results, however it is displaying as undefined in the HTML output

I have encountered a problem while working on my project. I am utilizing an API to fetch an array of platforms where a video game is available. Although the array is returning the correct data, I am facing difficulty in displaying these values in my HTML a ...