Passing both the value and index from a child component to a parent method is a

After reading an answer on Stack Overflow, I was able to successfully pass a value from a child component to the parent and call a method in the parent using that value. However, my challenge is that the child components are generated dynamically with the use of v-for, and I also need to pass the index of each component to the method along with the value.

This is what I am aiming for:

<component v-for="(component, index) in components" :key="index" 
:is="component" :index="index" @title-change="setTitle(value, index)" />

If I simply use

@title-change="setTitle"
, the value gets passed correctly to the setTitle method without needing to explicitly provide it as a parameter.

However, I also want to include the index in the method call. Unfortunately, none of the following attempts seem to work:

@title-change="setTitle(value, index)"
@title-change="setTitle(index, value)"
@title-change="setTitle(index)"

It's worth mentioning that I am working with Vue 2.

Answer №1

One way to create an object with index and title is by passing it to the parent:

Vue.component('Child', {
  template: `
    <div class="">
      <input v-model="title" />
      <button @click="titleChange">change</button>
      {{title}}
      {{index}}
    </div>
  `,
  props:['index'],
  data() {
    return {
      title: ''
    }
  },
  methods: {
    titleChange() {
      this.$emit('title-change', {idx: this.index, title: this.title})
    }
  }
})

new Vue({
  el: '#demo',
  data() {
    return {
      components: ['child', 'child', 'child']
    }
  },
  methods: {
    setTitle(val) {
      console.log(val)
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="demo">
  <component v-for="(component, index) in components" :key="index" 
:is="component" :index="index" @title-change="setTitle" />
</div>

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 mock URL in axios for unit testing purposes?

Scenario In this application, the URL is only accessible in production and cannot be accessed locally. During unit testing, it becomes necessary to mock the response from that URL. Solution Refer to this helpful tutorial for guidance. Current Implement ...

Exploring the Concept of Constructor Interfaces in TypeScript

I need some help with understanding constructor interfaces in TypeScript. I am new to this concept and I'm struggling to grasp how they are type checked. Let's take a look at an example from the documentation: interface ClockConstructor { ne ...

Tips on utilizing AngularJS $http for transferring multipart/form-data

In the process of creating a visual interface that interfaces with various REST services (coded in Java), I am encountering an issue when attempting to call one such service: @PUT @Path("serviceName") public Response serviceName(final FormDataMultiPart mu ...

When attempting to modify styles in IE10, I consistently encounter an error message stating "Unable to evaluate expression."

Below is a JavaScript function I have created to hide an HTML tag: function hideObject(objectId) { var obj = document.getElementById(objectId); if (obj) { obj.style.display = "none"; } } I encountered a strange issue when using this ...

What advantages does KnockoutJS offer over AngularJS?

Can KnockoutJS offer a unique feature that rivals or exceeds those of AngularJS? ...

Creating a modal component in VueJs integrated with Laravel

I am looking for assistance in implementing a VueJS modal component to remove something using a Laravel route. In my constructor, I have the destroy method but I need help on how to proceed with this. Can someone please guide me? Here is the code for my m ...

What is the proper location to place the .env file in a Vue3 CLI project?

I have recently completed a project using Vue3-CLI. In order to manage environment variables, I decided to utilize both the .env and .env.development files in my project structure. After setting up these files, however, I noticed that my variables such a ...

Locate every instance of items in an array within a string

My files have a structure similar to this: https://i.stack.imgur.com/KyaVY.png When a user conducts a search, they send an array to the backend. This array always includes at least one element. For example, if they send ['javascript'] to the b ...

What is the reason behind Typescript flagging a potential undefined value when checking for array length using a greater than comparison but not with an

Consider the following excerpt from a React component: const AccountInformation = (props: { readonly accountData: AccountData | undefined | null }) => { const hasMultipleAccounts: boolean = props.accountData?.customerAccounts?.length === 1 ? false : t ...

What are the functioning principles of older ajax file uploading frameworks (pre-html5)?

Traditional HTML includes an input element with a file type option. Tools are available that enable asynchronous file uploads with progress tracking. From what I gather, this is achieved by splitting the file into chunks and sending multiple requests wit ...

What is the best way to use jQuery AJAX to efficiently upload a file to a PHP page

Attempting to write some JavaScript code along with AJAX for file sending technology. Here is the HTML form code: <form action="" method="post" id="contact_form" enctype="multipart/form-data"> <input type="text" name="name" id="name"> < ...

Unpacking a props object results in an undefined value

I've been struggling to set up a data-grid in react because I'm facing issues with accessing the data from my props. Whenever I try to access or destructure the prop, it shows up as "undefined" in my console. This problem only arises when the p ...

I'm struggling to figure out the solution for this error message: "Unhandled Rejection (Type Error): Cannot read property 'filter' of undefined." Can someone please assist me with resolving this

Can you assist me? I am a beginner when it comes to javascript/React. I am currently following this tutorial https://github.com/Azure-Samples/js-e2e-client-cognitive-services and encountering the following error message: "Unhandled Rejection (TypeErro ...

Error: The DOM is throwing an uncaught TypeError because it cannot read the property 'children' of an undefined value

After delving into the depths of the DOM, I zeroed in on a specific element that I was eager to access. To reach this elusive element, I meticulously navigated through the DOM using the following code snippet: var body = document.body; var bodych ...

Conceal a div while revealing the other div

I am currently trying to achieve a unique visual effect. I have three divs named div1, div2, and div3. The objective is for div1 to slide up and disappear when clicked, while div2 simultaneously slides up and becomes visible. Similarly, when div2 is click ...

Tips for combining or adding duplicated values in a Javascript array

I am facing a problem with an array object that looks like this: [ {"item_id":1,"name":"DOTA 2 Backpack","image":"XXX","qty":1,"original_price":1450000,"total_price":1450000}, {"item_id":2,"name":"Mobile Legend Backpack","image":"XXX","qty":1,"origin ...

What is the process for transforming a JSON object format to another in node.js?

I found myself with a json object structured as follows: { "sample1": { "4": 2245, "5": 2175, "6": 3495, "7": 1845, ... "11.5": 1674, "12.5" ...

Issue with Foundation 6 not triggering the change.zf.slider event

Hey there, this is my first time posting and I could really use some help... I'm struggling to make the $("[data-slider]").on('change.zf.slider', function(){}); event trigger. I've attempted using the id of the element like so $(" ...

What is the best method for establishing a page location during rendering/onload?

It seems like there is a JavaScript event happening here using the onload attribute. But for the life of me, I can't seem to crack this code. <body onload="moveToHere('reference')"> I'm stuck and could really use some assistance ...

Retrieving an HTML page from one location and automatically populating textboxes with preexisting values on the receiving end

I'm currently facing a dilemma. Here's the issue: I need to load an HTML page (let's call it test.html) when a button is clicked on another page (referred to as home page). The test.html page has input boxes that I want to populate with p ...