How can we collect child component input data and store it in an array within a Vue.js parent component?

** To illustrate, when the button is clicked, a new component is added along with new data. Therefore, I would like to collect all this information into one array when I click the Save Data button. I hope this explanation makes sense.

<Child v-for="count in btnNumber" :key="count" @showData="getElements" />

<v-btn
  color="primary"
  elevation="10"
  class="space"
  large
  @click="duplicateEl"
  >Add Categ & Key</v-btn
>
v-btn
      color="secondary"
      elevation="13"
      class="btnEl"
      dark
      large
      @click="getResult"
      >Save Data</v-btn

** The data is obtained from the child component using Emit.

methods:{
               getElements(emitPayload) {
              this.selectedChildCategory = emitPayload.selectedCateg;
              this.selectedChildKey = emitPayload.selectedKey;
              this.selectedChildLanguage = emitPayload.selectedLang;
              this.selectedChildContent = emitPayload.selectedCon;
        }
    }
 duplicateEl() {
  this.btnNumber++;
}

https://i.sstatic.net/Yr5l5.png

https://i.sstatic.net/9iTYI.png

Answer №1

If you want to store data on the parent component, here is an example code snippet that demonstrates how it can be done:

Vue.component('Child', {
  template: `
  <v-form>
    <v-container>
      <v-row>
        <v-col>
          <v-select
            :items="categories"
            label="Category"
            dense
            outlined
            v-model="content.cat"
            @change="setD"
          ></v-select>
          </v-col>
          <v-col>
          <v-select
            :items="keys"
            label="Key"
            dense
            outlined
            v-model="content.key"
            @change="setD"
          ></v-select>
          </v-col>
          <v-col>
          <v-select
            :items="langs"
            label="Lang"
            dense
            outlined
            v-model="content.lang"
            @change="setD"
          ></v-select>
          </v-col>
          <v-col>
          <v-select
            :items="contents"
            label="Cont"
            dense
            outlined
            v-model="content.cont"
            @change="setD"
          ></v-select>
        </v-col>
      </v-row>
    </v-container>
  </v-form>
  `,
  props: ['conte'],
  data() {
    return {
      content: this.conte,
      categories: ['first', 'second', 'third'],
      keys: [1,2,3],
      langs: ['g', 'h', 'j'],
      contents: ['aaa', 'bbb', 'ccc']
    }
  },
  methods: {
   setD() {
      this.$emit('show', this.content);
    },
  },
})

new Vue({
  vuetify: new Vuetify(),
  el: "#app",
  data() {
    return {
      contentFields: [{id: 0, cat: '', key: '', lang: '', cont: ''}],
      showData: false
    }
  },
  methods: {
    addInput() {
      let newI = this.contentFields.length 
      this.contentFields.push({id: newI, cat: '', key: '', lang: '', cont: ''})
    },
    getElements(e){
      const newData = this.contentFields.map(obj => {
        if(obj.id === e.id) 
           return { ...obj }
        return obj
      });
    },
    getResult() {
      this.showData = !this.showData
    }
  }
})
<head>
  <link href="https://fonts.googleapis.com/css?family=Roboto:100,300,400,500,700,900" rel="stylesheet">
  <link href="https://cdn.jsdelivr.net/npm/@mdi/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e0868f8e94a0d6ce98">[email protected]</a>/css/materialdesignicons.min.css" rel="stylesheet">
  <link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1a6c6f7f6e737c635a283462">[email protected]</a>/dist/vuetify.min.css" rel="stylesheet">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no, minimal-ui">
</head>
<body>
  <div id="app">
    <v-app>
      <v-main>
        <v-container>
          <v-btn
            color="primary"
            elevation="10"
            class="space"
            large
            @click="addInput"
          >Add Categ & Key</v-btn>
          <v-container v-for="(content, i) in contentFields" :key="i">
            <child :conte="content" @show="getElements" />
          </v-container>
          <v-btn
            color="secondary"
            elevation="13"
            class="btnEl"
            dark
            large
            @click="getResult"
          >Save Data</v-btn>
          <div v-if="showData">{{ contentFields }}</div>
        </v-container>
      </v-main>
    </v-app>
  </div>

  <script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="562023331664782e">[email protected]</a>/dist/vue.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c1b7b4a4b5a8a7b881f3efb9">[email protected]</a>/dist/vuetify.js"></script>

Answer №2

Consider storing the emitted data in a new array variable and utilizing that for your operations

<template>
      <div>
        <Child
          v-for="count in btnNumber"
          :key="count"
          @showData="getElements(count)"
        />
        <!-- BUTTONS HERE -->
      </div>
    </template>
    <script>
    export default {
      data() {
        return {
          elementsEmittedDataArray: [], // Store emitted data in this array
        };
      },
      methods: {
        getElements(countIndex, emitPayload) {
          const data = {
            uniqueIndex: countIndex,
            selectedChildCategory: emitPayload.selectedCateg,
            selectedChildKey: emitPayload.selectedKey,
            selectedChildLanguage: emitPayload.selectedLang,
            selectedChildContent: emitPayload.selectedCon,
          };
          // Update or add data to the array based on uniqueIndex
          const index = this.elementsEmittedDataArray.findIndex(
              (element) => element.uniqueIndex === countIndex
          );
          if (index !== -1) {
              this.elementsEmittedDataArray[index] = data;
          } else {
              this.elementsEmittedDataArray.push(data);
          }
        },
        duplicateEl() {
          this.btnNumber++;
        },
    
        submitData(){
            // Utilize the stored array for further processing
            console.log(this.elementsEmittedDataArray);
        }
    
      },
    };
    </script>

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

Attempting to retrieve the styling for the placeholder attribute of a specific element

I am currently working on a project for a company's website that utilizes placeholder attributes. My main goal is to extract the color styling from this SPECIFIC ATTRIBUTE only, rather than from the input element itself. The style is applied using - ...

Update the values and attributes of DOM elements upon form submission

I have two text input fields: <input type="text" id="Title"/> <input type="text" id="URL"/> In addition, there is a dropdown menu and a submit button. The options in the dropdown menu are linked to elements on the page by their IDs. When yo ...

Organizing quiz inquiries within an array of objects

I'm currently working on developing a JavaScript quiz program. All of the questions are stored in an array, with each question being represented as an object containing the question itself, answer choices for the user to select from, and the correct a ...

Calculate the total price from a combination of HTML and JavaScript options without altering the values

I'm currently facing an issue in my form where the final price needs to be updated when a different option is selected. I've searched extensively for the problem without success. I've used similar code before, just with different variables a ...

Issue with Vue not updating state variable

I am facing an issue where the product.categories data is not being updated in the Vue Dev Console when the selectCategory method is called. <li class="border hover:bg-blue-100" v-bind:class="" v-on:click="selectCategory($event ...

Tips for resolving CORS issue when making calls to a third-party API in Nuxt 3

Currently, I am experimenting with Nuxt 3 and utilizing the useFetch hook to request data from an API. However, every time I attempt to call the 3rd party API endpoint https://apitest.bankfeeds.com.au/v1/customer/data using the useFetch hook, it results in ...

Require assistance with debugging an issue in an online game played through a web browser

Experience a simple browser memory game where you must flip all matching cards to emerge victorious. The glitch : In the game, if you click quickly enough, you can uncover more than two cards at a time. I've spent ample time attempting to rectify t ...

How can JavaScript be used to identify duplicate elements within an array?

In a recent interview, I was tasked with finding repetitive elements in an array. While I was able to do so using a for loop, the interviewer requested a more efficient method without using a for loop. I am relatively new to exploring Java script and would ...

Explore button that gradually decreases max-height

I have a "Show More" button that expands a div by removing the css attribute max-height, but I want to add an animation similar to jQuery's slideToggle() function to smoothly reveal the rest of the content. This is the code I am using: <div id="P ...

Exporting data from HTML tables with a simple click

I'm working on exporting an HTML table with a single click of a link. Currently, I am using , but I'm open to other suggestions as well. By including the following link, it creates a functional button for exporting the table. (If I set exportBu ...

jQuery tabs with carousel navigation

I am looking to enhance my jQuery tabs with a prev/next navigation in the form of a carousel. However, I am unsure of how to go about implementing this feature. Here is a snippet of my current code: Javascript <script type="text/javascript> ...

Assigning an array of objects within an AJAX request

I have a MediaObject object that includes: a Media object an array and a function called getMedia() When attempting to create a Media object and push it into the array inside the getMedia function after making an AJAX call, I encountered issues referenc ...

If an object is discovered in the array, increase its value; if not, add it to the array

I am facing a challenge with executing an updateOne() query on my database. The objective is to increment a specific value in a document if an object within an array in the document has an _id that matches a certain value. If there are no matches with that ...

Take action if the variable within the interval function contains a specific value

I need help troubleshooting a script issue I'm having. Here's the code snippet in question: i = 0; setInterval(function() { if(i < 100) { i++; } }, 1000); if(i == 100) { alert("done"); } <script src="https://a ...

The interaction issue in Ionic 4 with Vue js arises when the ion-content within the ion-menu does not respond to clicks

My Vue app has been set up with Ionic 4 using @ionic/vue. Below is the code snippet from the main.js file: import Vue from 'vue' import App from './App.vue' import router from './router' import store from './store&apos ...

What is the process of selecting a hyperlink?

Currently working on enhancing the functionality of my script. The main purpose of this script is to download a page using curl in PHP for authorization purposes. Once the page is downloaded, I need to interact with a button labeled "LOGIN" to input my log ...

React component refuses to re-render

I am facing an issue with my menu re-rendering in React. The handleToggleFunction only works for the first click, after which nothing happens and the state does not update. I am using Tailwind CSS in this component. Here is my code: I have attempted to us ...

Adding a CSS link to the Vue CLI build result

Currently, I am working on a project in Laravel that involves using Vue and Vuetify for the frontend. My setup includes using Vue CLI and configuring its output directory to be within Laravel's public folder through the use of vue.config.js. Here is h ...

Converting JSON to HTML without the use of external libraries

As a newcomer to JSON, I'm feeling quite puzzled by it. I need to transform a legitimate JSON string into a valid HTML string in order to display JSON on the web. jsonToHtml(“[{‘x’: 1, ‘b’: 2}, {‘x’: 100, ‘b’: 200}]") => “x:1x ...

Flask caches JSON files automatically

I am currently working on a visualization app using js and python. The functionality of my app is as follows: There is a textbox in the browser where I input an URL The URL is then sent to Python via Flask In Python, the URL is processed to create ...