How to dynamically add/remove slot fields based on arrays in Vue JS
P粉639667504
P粉639667504 2023-08-28 17:43:21
0
1
490
<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>
P粉639667504
P粉639667504

reply all(1)
P粉463824410

Add a unique key value to your v-for loop element:

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

This ensures that elements are correctly removed from the DOM.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template