How can VueJS dynamically incorporate form components within a nested v-for loop?

I've encountered a challenge while working on my project.

Here is the form I'm currently using:

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

Upon clicking the 'New Deal Section' button, a new section like this one is created:

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

My goal is to add multiple text boxes in each section when the 'New Item' button is pressed. I tried nesting a second v-for loop within the container generated by the 'New Deal Button,' but I couldn't make it work.

As someone who is new to JS and VueJS framework, I would greatly appreciate any assistance provided. Here is the code I have written so far:

<!--Start of content-->
        <div class="container">
            <button class="btn btn-success mt-5 mb-5" @click="addNewSection">
                New Deal Section
            </button>

            <div class="card mb-3" v-for="(section, index) in sections">

                <div class="card-body">
                    <button class="btn btn-success mt-5 mb-5" @click="addNewItem">
                        New Item
                    </button>

                    <span class="float-right" style="cursor:pointer">
                        X
                    </span>

                    <h4 class="card-title">Deal section {{ index + 1}}</h4>

                    <div class="employee-form" v-for="(addition, index) in additionals">
                        <input type="text" class="form-control mb-2" placeholder="Item" v-model="addition.item">
                    </div>

                    <div class="employee-form">
                        <input type="text" class="form-control mb-2" placeholder="Item" v-model="section.item">
                    </div>
                </div>
            </div>
        </div>

        <script>
            var app = new Vue({
                el: '.container',
                data: {
                    sections: [
                        {
                            item: '',
                        }
                    ]
                },
                methods: {
                    addNewSection () {
                        this.sections.push({
                            item: ''
                        })
                    },
                    addNewItem () {
                        this.additionals.push({
                            item: ''
                        })
                    }
                }
            })
        </script>

Answer №1

Make sure to include the additionals array within the sections array as shown below:

<div id="app">
    <div class="container">
        <button class="btn btn-success mt-5 mb-5" @click="addNewSection">
            New Deal Section
        </button>

        <div class="card mb-3" v-for="(section, index) in sections">
            <hr>
            <div class="card-body">
                <button class="btn btn-success mt-5 mb-5" @click="addNewItem(index)"> <!-- passing the index -->
                    New Item
                </button>

                <span class="float-right" style="cursor:pointer">
                    X
                </span>

                <h4 class="card-title">Deal section {{ index + 1}}</h4>

                <div class="employee-form" v-for="(addition, index) in section.additionals"> <!-- additionals of the section -->
                    <input type="text" class="form-control mb-2" placeholder="Item" v-model="addition.item">
                </div>

                <div class="employee-form">
                    <input type="text" class="form-control mb-2" placeholder="Item" v-model="section.item">
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    var app = new Vue({
        el: '.container',
        data: {
            sections: [
                {
                    item: '',
                    additionals: [] // <-
                }
            ]

        },
        methods: {
            addNewSection() {
                this.sections.push({
                    item: '',
                    additionals: [] // <-
                })
            },
            addNewItem(id) {
                // passing the id of the section
                this.sections[id].additionals.push({
                    item: ''
                })
            }
        }
    })
</script>

JSFiddle: https://jsfiddle.net/Wuzix/qs6t9L7x/

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

Is your Vuex state data not persisting properly?

I am currently developing an admin panel using Vue.js and utilizing Vuex for state management. store/module/home/home.js: import instance from "../../../services/Http"; const state = { usersCount: 0, customersCount: 0, chefsCount: 0, d ...

Converting MultiSelect Array from JavaScript to MySQL

I recently implemented a multiselect feature on the client side: <select name="country" data-placeholder="Choose a Country..." tabindex="2"> <option name="country" value="United States">United States</option> & ...

Using PHP, show a specific table row when clicked by matching the ID

I am currently developing an application for a school project that manages tests. This app allows employees to log in, select a client, register clients, and conduct tests with them, all while storing the data in a database. I have successfully implemente ...

Incorrect .offset().top calculation detected

Within a webpage, I have multiple sections. Positioned between the first and second section is a navbar menu. As the user scrolls down and the navbar reaches the top of the page, a function is triggered to fix it in place at the top. While this functionali ...

Updating device information in real-time using React Native

Currently, I am utilizing react-native-device-info to access the DeviceLocale or DeviceCountry. However, I am wondering if there is a method to update Device-info without requiring a complete restart of the app. For instance, when my device language is se ...

Exploring techniques to compare two objects in JavaScript and then dynamically generate a new object with distinct values

var person1={ name:"Sarah", age:"35", jobTitle:"Manager" } var person2={ name:"Sarah Sanders", age:"35", jobTitle:"Manager" } //the name value has been updated in the above object, s ...

Attempting to toggle variable to true upon click, but encountering unexpected behavior

On my webpage, I have implemented a simple tab system that is only displayed when the variable disable_function is set to false. However, I am facing an issue with setting disable_function to true at the end of the page using a trigger. When this trigger ...

What is the best way to manage photos from your phone without having to upload them online?

I'm currently developing an application using AngularJS/Javascript, HTML, and CSS within a cloud-based environment on c9.io. My next task is to create and test an app that can access the phone's photo album, apply filters to images, and I'm ...

Attempting to execute a synchronous delete operation in Angular 6 upon the browser closing event, specifically the beforeunload or unload event

Is there a way to update a flag in the database using a service call (Delete method) when the user closes the browser? I have tried detecting browser close actions using the onbeforeunload and onunload events, but asynchronous calls do not consistently wor ...

The regular expression used for validating domains does not function properly in the Safari browser

I am struggling with a JavaScript regular expression error that Safari is giving me. I am trying to validate a domain, but for some reason, this specific part (?<!-) is causing the issue because the domain name should not end with a hyphen. ^((?!-)[A-Z ...

Apexcharts - Blank space in area chart

I am currently facing an issue while trying to create an area chart using apexcharts on nuxt (vue2). The problem is that the area is not being filled as expected, and the options I have set in chartOptions for fill are affecting the line itself instead of ...

How can we make it simple for users to update webpage content using a file from their computer?

I am developing a custom application specifically for use on Firefox 3.6.3 in our internal network. My goal is to dynamically update the content of the page based on a file stored locally on my computer. What would be the most straightforward approach to ...

Convert the easeInExpo function from jQuery easing to vanilla JavaScript and CSS

Currently, I am in the process of converting a piece of code from jQuery to plain JavaScript and CSS. The specific code snippet I am focusing on involves creating easing functions without relying on jQuery. const customEasing = { easeInExpo: function ( ...

Utilize CSS in your HTML using Express framework

I am attempting to link a css stylesheet to my basic html webpage. I am utilizing parse.com hosting for dynamic webpages that utilize express. There are numerous responses to this question, but none of them have proven successful in my case. I am trying ...

Complete a checkbox entry form and showcase it within a "division" on the current page

Hello everyone, I need some help. I have a form that I want to send to a specific div on the same page. This is what I am aiming for. I have a floating div named "basket" in the top right corner of my page where I want the form data to be displayed after s ...

Generate a compressed folder containing a collection of PNG images

While attempting to generate a zip file using JSZip, I encounter issues where the images are falsely flagged as not being instances of Blob or the final result turns out to be corrupt and cannot be extracted. The process involves an API on the back-end th ...

Utilizing Chart.js for generating a sleek and informative line graph

After executing a MySQL query, I obtained two tables named table1 (pl_pl) and table2 (act_act) with the following data: table1: label act_hrs Jan-19 7 Feb-20 8 Mar-20 9 table2: label pl_hrs Mar-20 45 Apr-20 53 I am looking to create a line cha ...

Button for Toggling Audio Play and Pause

Is it possible to create an SVG image that changes color slightly when hovered over, and when clicked toggles to another SVG image that can be switched back to the original by clicking again with the same hover effect? Additionally, when clicked, it should ...

Leveraging React with axios instead of curl

Can a curl request be made using axios? The curl command is as follows: curl -v 'https://developer.api.autodesk.com/authentication/v1/authenticate' --data 'client_id=1234&client_secret=1234&grant_type=client_credentials&scope=b ...

Leverage the worker-loader in conjunction with vue-cli and webpack

Currently, I am in the process of setting up worker-loader with vue-cli webpack installation. The file structure for build / configuration looks like this: -build --vue-loader.conf.js --webpack.base.conf.js --other build files... -config --index.js --dev. ...