반응형
Vue 2의 컴포넌트 어레이에서 아이템을 추가 및 삭제하는 방법
my-item이라는 컴포넌트를 만들었습니다.이 컴포넌트에는 드롭다운('item List'로 입력됨)과 드롭다운에서 입력된 2개의 입력 상자가 포함되어 있습니다.이 구성 요소는 행으로 간주됩니다.
한 번에 1개의 행을 추가 및 삭제하려고 합니다만, 2개의 점에 대해서는 잘 모르겠습니다.(1) 행 배열에 추가할 것은 무엇입니까?(2) 이 .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?
}
}
})
몇 가지 실수가 있습니다.
- 의 어레이에 적절한 개체를 추가해야 합니다.
addRow
방법 - 사용할 수 있습니다.
splice
특정 인덱스의 배열에서 요소를 제거하는 메서드입니다. - 현재 행을 소품으로 전달해야 합니다.
my-item
컴포넌트, 여기서 변경할 수 있습니다.
여기서 작업 코드를 볼 수 있습니다.
addRow(){
this.rows.push({description: '', unitprice: '' , code: ''}); // what to push unto the rows array?
},
removeRow(index){
this. itemList.splice(index, 1)
}
사용할 수 있습니다.Array.push()
요소를 배열에 추가합니다.
삭제할 경우 사용하는 것이 가장 좋습니다.this.$delete(array, index)
사용할 수 있습니다.
: 객체의 속성을 삭제합니다
Vue.delete( target, key )
.개체가 반응하는 경우 삭제 트리거가 업데이트 보기를 트리거하는지 확인합니다.이는 주로 Vue가 속성 삭제를 감지할 수 없다는 제한을 피하기 위해 사용되지만 거의 사용할 필요가 없습니다.
https://vuejs.org/v2/api/ #Vue-delete
언급URL : https://stackoverflow.com/questions/41374363/how-to-add-and-remove-item-from-array-in-components-in-vue-2
반응형
'programing' 카테고리의 다른 글
IntelliJ IDEA에서 Eclipse의 Ctrl+O(개요 표시) 단축키는 무엇입니까? (0) | 2022.08.28 |
---|---|
vuex 스토어 데이터를 리셋/삭제하려면 어떻게 해야 합니까? (0) | 2022.08.27 |
Vuex가 기존 양식 데이터를 상태별로 로드하여 편집 (0) | 2022.08.27 |
Vuejs 프로젝트 빌드가 서버에서 작동하지 않음 (0) | 2022.08.27 |
Linux에서 addr2line 명령을 사용하는 방법 (0) | 2022.08.27 |