search

Home  >  Q&A  >  body text

How to dynamically add/remove slot fields based on arrays in Vue JS

<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粉639667504P粉639667504457 days ago491

reply all(1)I'll reply

  • P粉463824410

    P粉4638244102023-08-29 12:59:04

    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.

    reply
    0
  • Cancelreply