How to dynamically add/remove slot fields based on arrays in Vue JS
P粉639667504
2023-08-28 17:43:21
<p>I have the following code, which accepts a slot containing an HTML field to be repeated: </p>
<pre class="brush:php;toolbar:false;"><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></pre>
<p>When I use <code>removeRow(index)</code>, it always removes the last slot. I've tested using <code><input v-model="row.value"></code> and the correct input was removed here, but the correct slot was never removed. </p>
<p>I don't need the input in the slot to be dynamic or interact with Vue, I just want to allow the user to dynamically add/remove rows via the Vue component. </p>
<p>Please take a look at the two methods I use to add/remove rows below, in case this is the problem: </p>
<pre class="brush:php;toolbar:false;">removeRow(index){
this.rows.splice(index, 1);
},
addRow(){
this.rows.push({value: 'test'})
}</pre>
<p>Any help is greatly appreciated. </p>
Add a unique
key
value to yourv-for
loop element:This ensures that elements are correctly removed from the DOM.