I have the following, which takes a slot containing the HTML fields to be repeated:
JavaScript
x
11
11
1
<div v-for="(row, index) in rows" :key="index">
2
<div class="d-flex justify-content-between ">
3
<slot name="fields">
4
</slot>
5
<input v-model="row.value" />
6
<button @click="removeRow(index)" type="button" class="btn btn-primary waves-effect waves-float waves-light height-10-per " >
7
Remove <i class="fa fa-times-circle"></i>
8
</button>
9
</div>
10
</div>
11
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:
JavaScript
1
7
1
removeRow(index){
2
this.rows.splice(index, 1);
3
},
4
addRow(){
5
this.rows.push({value: 'test'})
6
}
7
Any help would be really appreciated.
Advertisement
Answer
Add a unique key
value to your v-for
loop element:
JavaScript
1
2
1
<div-for="(row, index) in rows" :key="JSON.stringify(row)">
2
This should make sure the correct element is removed from the DOM.