2016-12-29 9 views
4

コンポーネント "my-item"には、ドロップダウン( "itemList"によって作成)とドロップダウンから入力された2つの入力ボックスが含まれています。 このコンポーネントは行と見なされます。Vue 2のコンポーネントの配列にアイテムを追加して削除する方法

私は一度に1つの行を追加して削除しようとしていますが、わかりません。 (1)行配列に何を追加しますか? (2)this.rows.splice(index、1)はなぜ最後の行だけを削除していますか?

https://jsbin.com/mugunum/edit?html,output

おかげ

<div id="app"> 
    <my-item v-for="(row, index) in rows" 
     :itemdata="itemList" 
      v-on:remove="removeRow(index)"> 
    </my-item> 
<div> 
    <button @click="addRow"> Add Row </button> 
</div> 
</div> 

<template id="item-template"> 
<div> 
    <select v-model="selected"> 
     <option v-for="item in itemdata" :value="item"> 
      {{ item.code }} 
     </option> 
    </select> 
    <input type="text" placeholder="Text" v-model="selected.description"> 
    <input type="text" placeholder="value" v-model="selected.unitprice"> 
    <button v-on:click= "remove"> X </button> 
</div> 
</template> 

Vue.component('my-item', { 
props: ['itemdata'], 
template: '#item-template', 
data: function() { 
    return { 
    selected: this.itemdata[0] 
    } 
}, 
methods: { 
    remove() { 
     this.$emit('remove'); 
    } 
} 
}), 

new Vue({ 
el: "#app", 
data: { 
    rows: [], 
    itemList: [ 
     { code: 'Select an Item', description: '', unitprice: ''}, 
     { code: 'One', description: 'Item A', unitprice: '10'}, 
     { code: 'Two', description: 'Item B', unitprice: '22'}, 
     { code: 'Three', description: 'Item C', unitprice: '56'} 
    ] 
}, 

methods: { 
    addRow(){ 
     this.rows.push(''); // what to push unto the rows array? 
    }, 
    removeRow(index){ 
     this.rows.splice(index,1); // why is this removing only the last row? 
    } 
} 
}) 

答えて

8

あなたがやっているいくつかのミスがあります:

  1. をあなたがaddRowメソッドを使用でき
  2. に配列内の適切なオブジェクトを追加する必要がsplice特定のインデックスでremove an element from an arrayに変更します。
  3. 現在の行を小道具としてmy-itemコンポーネントに渡す必要があります。このコンポーネントは変更可能です。

作業コードhereが表示されます。

addRow(){ 
    this.rows.push({description: '', unitprice: '' , code: ''}); // what to push unto the rows array? 
}, 
removeRow(index){ 
    this. itemList.splice(index, 1) 
} 
+0

私はそれを試しましたが、それでもなお真実は得られません。 – Pyol7

+0

@ Pyol7行内に何かを押しているわけではありません。削除するインデックスの違いを知るよりも、まず行を正しく追加する必要があります。 – Saurabh

+0

それは問題です。私はaddRowを修正する方法を知らない – Pyol7

関連する問題