Communication from a VueJS parent to its child component

I am new to VueJS and seeking advice on the most effective approach to use.

Within a parent component, I have multiple child components.

After creating the child components, each one has an event handler attached to it:

this.$parent.$on('save', this.save);

This allows us to call the save method of each child whenever we emit the following in the parent:

this.$emit('save', block);

The issue I am encountering is that every child listening to events from this parent reacts to this event. Is there a more efficient way to ensure only a specific child responds to the parent click event?

Answer №1

One approach to consider is passing a prop with the .sync modifier to a child component, where you could then utilize a computed property. However, it's important to understand your specific goal - do you truly need to emit an event for this functionality?

For more information on props in Vue.js, refer to the official documentation: https://v2.vuejs.org/v2/guide/components.html#Props

Answer №2

When tackling your current task, it could be beneficial to utilize a Child Component ref and trigger a method on the child component from the parent:

Vue.component('my-comp', {
  template: "#my-comp-template",
  props: ['name'],
  methods: {
    saveMyComp() {
      console.log('Saved:', this.name);
    }
  }
})

new Vue({
  el: '#app',
  data: {
    people: [{name: 'Bob'}, {name: 'Nelson'}, {name: 'Zed'}]
  },
  methods: {
    saveChild(index) {
      this.$refs.myComps[index].saveMyComp();
    }
  }
});
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5b2d2e3e1b69756e756a68">[email protected]</a>/dist/vue.min.js"></script>

<div id="app">
  <div v-for="(person, index) in people">
    <button @click="saveChild(index)">saveMyComp</button>
    <my-comp :name="person.name" ref="myComps"></my-comp>
  </div>
</div>

<template id="my-comp-template">
    <span> {{ name }} </span>
</template>

Do keep in mind that the parent is already connected to the child component as it is declared within the template.

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

Efficiently updating database records without the need for page reloads using EJS

I'm working on a project that resembles the comment section on Reddit. Users can leave comments and others can reply to those comments. My tech stack includes Node, Express, MySQL, and EJS. The issue I'm facing is implementing the upvote/downvo ...

JavaScript code to determine if a Rating is enabled for a SharePoint Online list

Currently, I am working on a JavaScript code that will allow users to provide star ratings for specific articles through a widget. One of the requirements is to first verify if the Rating feature is enabled for a particular SharePoint list. If it is enable ...

ERROR: Unable to use import statement outside a module in REACT-APP

Every time I attempt to print it out on a browser, I encounter an error in the header saying "Uncaught SyntaxError: Cannot use import statement outside a module." Prior to posting this question, I tried various solutions related to this issue, such as addi ...

What is the best way to adjust the size of an SVG path when zooming in Highcharts?

Recently, I developed a module that allows users to draw an svg line over a highchart using the Renderer. However, I encountered an issue where the size and position of the drawn line remain static when the user zooms into the highchart. It is essentia ...

Validation of dynamically added form fields in React

I recently developed a form in React with 2 fields, and I have successfully implemented functionality to add two more fields when the "add" button is clicked. However, I am now facing the challenge of validating these additional fields. Can anyone provide ...

Encountering an error message that says "ERROR TypeError: Cannot read property 'createComponent' of undefined" while trying to implement dynamic components in Angular 2

I am currently facing an issue with dynamically adding components in Angular 4. I have looked at other similar questions for a solution but haven't been able to find one yet. The specific error message I am getting is: ERROR TypeError: Cannot read ...

Developing React components in TypeScript in a dynamic manner

Is there a way to dynamically create components using React and TypeScript? If I have a RandomComponent and pass it as props to renderInput, how can I return <RandomComponent>? This snippet of code doesn't seem to work: export const renderInput ...

What can you do to ensure Vue detects input element changes after using preventDefault?

In this example, I am trying to prevent a newline from being created in a textarea when the Enter key is pressed. To achieve this, I use the preventDefault method in my event handler and update the value inside the textarea. However, I encounter an issue w ...

Unable to execute app.get in Express framework of Node.js

const express = require('express'); let router = express.Router(); router.get('/create-new', (req, res, next) => { res.send('<form action="/submit-data" method="POST"><input type="text" name="name"><button ...

Access the value of a JavaScript global variable using Selenium in Python

I need to access a value from a global variable in JavaScript: clearInterval(countdownTimerTHx); var saniye_thx = 298 // <--- Variable here function secondPassedTHx() { https://i.sstatic.net/odIbh.png My goal is to retrieve the value " ...

How to extract the value of an object from an array using jQuery

I have a set of four input fields: <input type="text" class="kal" name="data[tex1]"> <input type="text" class="kal" name="data[tex2]"> <input type="text" class="kal" name="data[tex3]"> <input type="text" class="kal" name="data[tex4]"& ...

Retrieving a compilation of items found within text selected by the user on a website

Imagine a scenario in which a webpage contains the following structure: <p> <span class="1">Here's some text</span> <span class="2">that the user</span> <span class="3">could select.</span> </p> I ...

Preventing Text Truncation in THREE.js Texture Created from 2D Canvas

Many people tend to use the 2D canvas texture method for creating text billboards, sprites, and overlays in THREE.js scenes instead of relying on imported image files. You can check out an example by Lee Stemkoski here. However, I have noticed that when a ...

Getting Started with Angular and Express

I've been able to easily set up Angular in my web app using ASP/Visual Studio, but I'm interested in delving into the world of Node, specifically Express. However, I'm struggling to grasp the concept of a basic route handler for Express that ...

`returning a functional component directly from a component's event listener`

Recently, I started exploring React and came across an issue with React Router integration. I have a React menu component that includes hyperlinks in a sidenav for navigation to other components. However, the standard React Routing method doesn't see ...

Swirling hues transforming into #000000 upon second attempt

My goal is to create a button that generates two random color codes. Initially, this button seems to work fine on the first click, but on the second click, both codes turn into #000000. Despite my attempts to troubleshoot the issue, I haven't been ab ...

When using Laravel and Vue in Javascript, the Array Length function may sometimes return an undefined

I'm currently immersed in a project utilizing Vue + Laravel, where I rely on axios for handling AJAX requests to fetch data from controllers and showcase it on the Javascript side. However, when employing nested for loops, I encounter some peculiar be ...

Error encountered: Cannot load Bootstrap date time picker in MVC due to ReferenceError: $ is not defined

My issue arises when trying to incorporate the bootstrap date time picker - the calendar fails to load upon clicking on the "glyphicon glyphicon-calendar" icon. Despite adding all necessary files, an error persists: Uncaught ReferenceError: $ is not de ...

Guide to ensuring every request in an Express.js application contains a cookie

Currently, I am in the process of developing a CRUD application using both React and Node. As part of my development, it is crucial for me to validate whether the cookie is present or not for each request. app.all("*", (req,res) => { // If the cookie ...

Prevent Jquery nth-child from impacting nested elements

Here is an issue I am currently dealing with in my code. I need to insert some text after the second paragraph, excluding the blockquote. Currently, when using jQuery, the new text appears after both the 2nd paragraph in content and the 2nd paragraph in th ...