Binding arguments to child functions within Vue components

When working with React, it's a common practice to bind parameters for child components in the following manner:

<Child onChange={e =>
  doThing(complex.variable.inParentScope[3], e.target.value)} foo="bar" />

In Vue, I want to achieve a similar functionality to ensure that child components remain as simple as possible (just needing to call onClick={(e) => onChange(e)}. However, I've come across information suggesting that passing functions as props is not recommended in Vue. I am struggling to figure out how to bind the arguments from the parent component to make the code reusable. Ideally, I would like to do something like this:

[1,2,3,4,5,dataFromAPI].map(data =>
  <Child change=& quot;e => handleChange(data, foo, e.target.value) />

Can someone provide guidance on how to achieve this?

Answer №1

It is perfectly acceptable, in my opinion, to pass a function to a child component. The reason why this may not be commonly seen in Vue is due to the availability of the $emit() method. Here's an illustration:

Vue.config.devtools = false;
Vue.config.productionTip = false;
Vue.component('child', {
  template: `<input @change="$emit('some-event', $event.target.value)" />`,
});

new Vue({
  el: '#app',
  data: () => ({
    myList: [1, 2, 3]
  }),
  methods: {
    someFn(item, index, value) {
      console.log({item, index, value});
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.12/vue.js"></script>
<div id="app">
  <child v-for="(item, index) in myList"
         :key="index"
         @some-event="someFn(item, index, $event)" />
</div>

The child component is designed to be as simple as possible (unaware of list context, index, or parent behavior with emitted values). Its focus is solely on its own value and emitting when necessary.

Keep in mind that $emit() does not bubble. For broader communication needs, consider store dispatching/committing or event bus usage.

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

AngularJS: The art of object pushing

I have a small application where I need to read data from a JSON file, display it, and allow users to add records to it. Specifically, I have an array called condition within the patient object, and I want to insert a new item into this array based on user ...

CSS hover effect ceases to function after the button has been clicked once

I am facing a dilemma with styling that I can't seem to resolve. There is a basic toggle feature on my page with two options -- the user can select either Toggle1 or Toggle2, resulting in different data being displayed dynamically based on the active ...

Issue in Vue/Node application: Rule is restricted to a single resource source

I just recently started diving into Vue and Node, and things were going smoothly with a Vue3 project I was experimenting with to enhance my skills. I decided to incorporate scss files, so I went ahead and installed sass-loader via npm using: npm install sa ...

Footer div is being covered by the page

I am currently working on a website built with "WordPress", and I have implemented a mobile footer plugin that is designed to only appear on mobile devices. However, I am encountering an issue where the page content overlaps the footer on phones. I attemp ...

Retrieve anchor elements from multiple HTML documents

I have a challenge that I'm not certain is achievable, but I am attempting to extract all anchor tag links from several HTML files on my website. Currently, I have developed a PHP script that scans various directories and subdirectories to create an a ...

Attempting to showcase a PDF document within a web browser

I am a newcomer to JavaScript and I'm encountering an issue with displaying a PDF file in the browser. Every time I try to do so, I keep receiving the same error message 'Cannot GET...' Despite trying various methods... router.get("/en ...

Using an array of references in React

I've encountered a problem where I'm trying to create a ref array from one component and then pass it to another inner component. However, simply passing them as props to the inner component doesn't work as it returns null. I attempted to fo ...

Eliminate JSON data that pertains to dates that are either in the past or future

I am working on integrating upcoming classes and past classes components into my application. I have successfully stored the schedule of classes and can retrieve them using backend services. However, I need to display only the upcoming classes in one compo ...

Two components, one scroll bar, both moving within the same plane

For those interested, here is the JSFiddle link for further exploration: https://jsfiddle.net/q6q499ew/ Currently, there is a basic functionality in place where when you scroll past a certain point, an element becomes stuck until you start scrolling back ...

Why is it that despite passing all the unit tests successfully, the function fails when used in its actual context with the same parameters?

I have created a basic API to encrypt text using the Caesar cipher in Javascript with Express.js. While running tests with Jest, it seems that all the tests are passing successfully (and a console.log of the output confirms that the resulting string matche ...

Creating a visually dynamic stack of images using javascript, jquery, and HTML

I'm interested in creating a unique image viewer using javascript/jQuery/HTML that combines elements of a book page flip and iTunes coverflow, optimized for mobile device browsers. I've been searching for tutorials to help kickstart this project, ...

Preventing page re-rendering with redux when a condition is not met

I am currently working on a page that features a question paper with multiple options and a button to navigate to the next question. import Grid from "@material-ui/core/Grid"; import Typography from "@material-ui/core/Typography"; import React, { useEffec ...

"An error has occurred stating that the header is not defined in

It is a coding issue related to payment methods. The headers type is undefined in this scenario, and as a newcomer to typescript, pinpointing the exact error has been challenging. An error message is indicating an issue with the headers in the if conditio ...

Transmitting the Flag between PHP and JavaScript

I need help with setting a flag in PHP and accessing it in JavaScript. Currently, I have the following code: PHP if ($totalResults > MAX_RESULT_ALL_PAGES) { $queryUrl = AMAZON_SEARCH_URL . $searchMonthUrlParam . ...

A step-by-step guide on implementing the bootstrap paginator library to paginate PHP echoed data

I'm currently working on a project that involves displaying data from a database in a table. To make the data paginated on the client side, I decided to use the bootstrap paginator library available at: Below is the code I'm using: In my header ...

Is it necessary to compile the React JavaScript project before uploading it to npm?

Hey there, I'm currently in the process of publishing a React JavaScript component on npm. I have a question regarding whether or not I need to build the project and deploy the build folder. Your input would be greatly appreciated. Thanks! ...

Creating a minigame using JQuery (Javascript)

I am currently developing a collection of mini-games for my big project. The approach I've taken in creating this mini-game is similar to one I used previously. However, unlike my previous version which only had one PuzzleContainer, this new iteration ...

Limit the application of the map() function to a single column within a 2-dimensional array in JavaScript when using Find and Replace

I have been using Google Sheets for my work Recently, I came across a find and replace function that I found here. This function works perfectly when the array is generated from a single column of data. However, there are certain cases where I need to us ...

Lustrous Layout

I am developing a mobile app using titanium where I have a scroll view containing objects that occupy 25% of the screen width. I am attempting to create a 'table' layout with these objects, having 4 columns and multiple rows. Is there a way for t ...

Executing multiple click events using JavaScript

I have recently started learning JavaScript and am experimenting with the following script: <script type="text/javascript"> $(document).ready (function() { $('#apply').click(function() { $('#applyinfo').toggle ...