I have the following, which takes a slot containing the HTML fields to be repeated:
<div v-for="(row, index) in rows" :key="index"> <div class="d-flex justify-content-between "> <slot name="fields"> </slot> <input v-model="row.value" /> <button @click="removeRow(index)" type="button" class="btn btn-primary waves-effect waves-float waves-light height-10-per " > Remove <i class="fa fa-times-circle"></i> </button> </div> </div>
When I use removeRow(index)
, it always removes the last slot. I’ve tested with using the <input v-model="row.value">
and the correct input is removed here, but never the correct slot.
I do not need the inputs in the slot to be dynamic or interact with Vue, I simply want to allow the user to add new rows/remove rows dynamically via a Vue component.
Please see the below two methods I’ve used for adding/removing rows, in case an issue lies here:
removeRow(index){ this.rows.splice(index, 1); }, addRow(){ this.rows.push({value: 'test'}) }
Any help would be really appreciated.
Advertisement
Answer
Add a unique key
value to your v-for
loop element:
<div-for="(row, index) in rows" :key="JSON.stringify(row)">
This should make sure the correct element is removed from the DOM.