2016-12-29 2 views
4

드롭 다운 ("itemList"로 채워짐)과 드롭 다운에서 채워진 두 개의 입력 상자의 세 가지 요소가 포함 된 구성 요소 "my-item"을 만들었습니다. 이 구성 요소는 행으로 간주됩니다.Vue 2의 구성 요소에서 배열의 항목을 추가 및 제거하는 방법

한 번에 한 행을 추가하고 삭제하려고하는데 두 가지가 확실하지 않습니다. (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

몇 가지 실수 당신이하고있는이 있습니다 :

  • 당신은 splice을 사용할 수 있습니다

    1. 당신은 addRow 방법으로 배열에 적절한 개체를 추가 할 필요가 특정 인덱스에서 remove an element from an array으로 변경하십시오.
    2. 이 행을 수정할 수있는 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

    관련 문제