Vue component with a variable number of rows, each containing a variable number of input fields

I am currently working on creating a form that can have a variable number of steps. Users should be able to add an additional step by clicking a button. Each step will contain some input fields and buttons to dynamically create more input fields.

For instance, there could be input fields for 'title' and 'description', along with a link to 'Add a Video' which, when clicked, would generate another input field and change the link to 'Remove the Video'.

All these steps need to contribute to creating an array of objects where each object may have slightly different properties. As someone new to vue, this process is quite bewildering for me.

<div v-for="(row, index) in rows" :key="index">

<input type="text" v-model="row.title">
<input type="text" v-model="row.description">
<div v-show="row.video">
    <input type="text" v-model="row.video">
</div>
    <a v-on:click="addVideo(index);" style="cursor: pointer">Add Video element</a><br>

<a v-on:click="removeElement(index);" style="cursor: pointer">Remove</a>
</div>
<div>
    <button class="button btn-primary" @click="addRow">Add Step</button>
</div>

Here are the functions associated with my code:

addRow () {
  this.rows.push({
    title: '',
    description: '',
    file: {
      name: 'Choose File'
    }
  })
},
addVideo (index) {
  this.rows[index].video = ' '
  this.$forceUpdate()
},
removeElement (index) {
  this.rows.splice(index, 1)
}

You can find the code snippet at this link: http://jsbin.com/punekukayu/1/edit?html,js,output

Currently, I am struggling with figuring out how to effectively remove the 'Add Video element' link from a step, as I suspect my approach might not be ideal.

Answer №1

To toggle between adding a video element and input field you can use v-if and v-else:

<a v-if="input.video === null" v-on:click="addVideo(index);" style="cursor: pointer">Add Video element</a>
<template v-else>
    <input type="text" v-model="input.video">
    <a v-on:click="removeVideo(index);" style="cursor: pointer">Remove Video element</a>
</template>

In order to avoid calling $forceUpdate, make sure to initialize video as null in the inputs:

addRow() {
  this.inputs.push({
    one: '',
    two: '',
    video: null                     // initialization
  })
},
addVideo (index) {
  this.inputs[index].video = '';    
},
removeVideo (index) {
  this.inputs[index].video = null;  
},

Check out the Updated JSBin here.


Consider passing each input directly to addVideo or removeVideo instead of using index. It can potentially simplify the code structure: http://jsbin.com/pucohawuje/1/edit?html,js,output - However, this is just a suggestion based on preference.

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

Ways to emphasize the contrast between two texts using CSS

One method to highlight specific parts of text using CSS can be found in this script: span.highlight { background-color: #B4D5FF; } However, what if we want to highlight the differences between two strings? Take for example these two strings: this ...

Despite implementing CORS, my POST request to expressjs is still not functioning properly

I have a function in my component that is responsible for sending a POST request to an express API: onSubmit (evt) { evt.preventDefault(); //alert(JSON.stringify(this.description)); axios.post('http://localhost:3000/api/v1/addCom ...

Looking to display a div with a unique timer?

Is there a way to display different divs with unique classes for specific durations of time? For example, I want one div to show for 2000 ms with the class 'one', then another div to show for 4000 ms with the class 'two', followed by a ...

What is the reason for the countdown number's color remaining the same even after it reaches a specific time threshold?

Creating a simple countdown for sports was my idea, but now I'm stuck on the "changeColor" part that I don't have enough knowledge about. The countdown is functioning perfectly, but customizing the colors and adding CSS animations seems challeng ...

What is the best way to combine objects that share the same id?

View Image: Displaying Image POST ID's https://i.stack.imgur.com/JO5OF.png I attempted to resolve this using jQuery each, but I am uncertain about the next steps. Check out my Code: jQuery(document).ready(function($) { var data, exampleData, , ...

Persistent navigation once fullscreen banner is completed

I have a full screen header on my one-page website. Below the hero section is the navigation element, which I want to be fixed after scrolling past the height of the full screen. Here's what I currently have in terms of code. HTML: <div id="hero" ...

Enhancing the functionality of localStorage

I am attempting to append a value to a key within the HTML5 localStorage. Take a look at my code below: var splice_string = []; splice_string += "Test value"; var original = JSON.parse(localStorage.getItem('product_1')); origina ...

Attempting to implement a smooth fade effect on my image carousel using React-Native

Struggling to animate this image carousel in reactNative and feeling lost. Despite reading the documentation on animations, I can't figure out how to implement it properly. My attempts keep resulting in errors. Any assistance would be greatly apprecia ...

The hyperlink does not function properly when included within an <input type=button> element

I have encountered an issue with the code below. In my project, I have a search bar along with some buttons. Currently, only the hyperlink of the search button is functioning correctly. The other buttons seem to redirect to the same link as the search bu ...

Trigger a popup using the javascript .link() method

I am currently using ag-grid to present JSON data. When the values are located within nested objects, I have to utilize a valueGetter from the grid API to map to the appropriate value. The value getter returns a value for each row and the grid matches it t ...

Unable to iterate through array using jQuery promise (when > then) due to issues with $.each and $.ajax

I have been experimenting with different approaches and searching for solutions without success. Currently, I am working with an array of users: var arr = ['tom', 'sally', 'jill', 'sam', 'john']; My goal ...

Middle-Click JavaScript Action

On the website I'm currently working on, there is a button that uses a sprite sheet animation and therefore needs to be set as a background image. I want the button to have a slight delay when clicked, so the animation can play before redirecting to a ...

Page elements subtly move when reloading in Chrome

I am experiencing an issue with a div that has left and top offsets randomly selected from an array of values upon page load. Most of the time, it works fine. However, occasionally, upon refreshing the page, the window scrolls down slightly, revealing the ...

Client-side filtering of jqGrid with multiple conditions

I am faced with a challenge in filtering records in a jqGrid based on multiple conditions. For example, if there are columns for Name, Age, and City, and I need to filter the grid using the following condition: Name = "Mark" and Age = 25 and City = &apos ...

Extra spaces within the source code visible after the page has been processed by Angular

Within my angular application, I am retrieving a list of addresses from a service that provides an object structured like this: { Flat: "10B", BuildingName: "Some Building", Line: "10B Some Building Road Town POST CODE", Postcode: "POST CODE", ...

Ways to prevent the loading of images during webpage loading

I have encountered an issue with my eCommerce site developed using Laravel 7. Whenever I click on the category page, all product images are being loaded, causing high bandwidth usage. The category "Appereal" contains over 100 products, and although I imple ...

Rendering lists in Vuejs2 with computed properties for filtering

I'm struggling with list rendering and filtering data using computed properties. Instead of statically setting the row.age value, I want to filter based on filterKey. Any guidance on how to achieve this? I'm having trouble understanding it. He ...

The absence of Div element is noticed when deploying the v-if statement

<div class="min-h-screen flex" ref="mapDiv"></div> <div class="bg-white absolute top-0 w-full overflow-y-auto"></div> This is the visual representation: https://i.sstatic.net/6GGJe.png When I include ...

Adjust the cell text overflow based on the width of the table

I am working with a table that has multiple columns. I want the first 3 columns to have a larger width than the others, specifically taking up 15% each for a total of 45% of the table's width. Currently, I am using this code in a sandbox environment: ...

CORS blocked in the live environment

error + whole page As a newcomer to JavaScript, I recently deployed my project. During development, everything was functioning well. However, I am now facing an issue with CORS when attempting to sign in (registration works without any problems, confirmin ...