首頁  >  問答  >  主體

Vue JS中如何根據數組動態新增/刪除插槽字段

<p>我有以下程式碼,它接受一個包含要重複的HTML欄位的插槽:</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>當我使用<code>removeRow(index)</code>時,它總是移除最後一個插槽。我已經測試了使用<code><input v-model="row.value"></code>,正確的輸入在這裡移除了,但從未移除正確的插槽。 </p> <p>我不需要插槽中的輸入是動態的或與Vue交互,我只是想允許用戶透過Vue組件動態添加/刪除行。 </p> <p>請看我用來新增/刪除行的下面兩種方法,以防問題出在這裡:</p> <pre class="brush:php;toolbar:false;">removeRow(index){ this.rows.splice(index, 1); }, addRow(){ this.rows.push({value: 'test'}) }</pre> <p>非常感謝任何幫助。 </p>
P粉639667504P粉639667504417 天前464

全部回覆(1)我來回復

  • P粉463824410

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

    為您的 v-for 迴圈元素新增一個獨特的 key 值:

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

    這樣可以確保從 DOM 中正確地移除元素。

    回覆
    0
  • 取消回覆