[javascript] Vue.js의 배열에서 항목을 제거하는 방법

저는 vue.js (2)를 처음 사용하고 현재 간단한 이벤트 앱을 작업 중입니다. 이벤트를 추가했지만 이제는 버튼을 클릭하여 이벤트를 삭제하고 싶습니다.

HTML

    <div class="list-group">

        <div class="list-group-item" v-for="event in events">
            <h4 class="list-group-item-heading">
                {{ event.name }}
            </h4>

            <h5>
                {{ event.date }}
            </h5>

            <p class="list-group-item-text" v-if="event.description">{{ event.description }}</p>

            <button class="btn btn-xs btn-danger" @click="deleteEvent(event)">Delete</button>
        </div>

    </div>
</div>

JS (Vue)

new Vue ({
    el: '#app',

    data: {
        events: [
            {
                id: 1,
                name: 'Event 1',
                description: 'Just some lorem ipsum',
                date: '2015-09-10'
            },
            {
                id: 2,
                name: 'Event 2',
                description: 'Just another lorem ipsum',
                date: '2015-10-02'
            }
        ],

        event: { name: '', description: '', date: '' }
    },

    ready: function() {

    },

    methods: {

        deleteEvent: function(event) {
                this.events.splice(this.event);
        },

        // Adds an event to the existing events array
        addEvent: function() {
            if(this.event.name) {
                this.events.push(this.event);
                this.event = { name: '', description: '', date: '' };
            }
        }

    } // end of methods

});

나는 이벤트를 함수에 전달하려고 시도했고 슬라이스 함수로 그 이벤트를 삭제하는 것보다 배열에서 일부 데이터를 삭제하는 코드라고 생각했습니다. simpleb 버튼과 onclick 이벤트로 배열에서 데이터를 삭제하는 가장 깨끗한 방법은 무엇입니까?



답변

splice잘못된 방식으로 사용 하고 있습니다.

과부하는 다음과 같습니다.

array.splice (시작)

array.splice (start, deleteCount)

array.splice (start, deleteCount, itemForInsertAfterDeletion1, itemForInsertAfterDeletion2, …)

시작은 제거 할 요소가 아니라 시작하려는 색인을 의미합니다. 그리고 두 번째 매개 변수 deleteCount를 1로 전달해야 합니다. 이는 “인덱스 {start}에서 시작하는 1 개의 요소를 삭제하고 싶습니다”를 의미합니다.

따라서 다음을 사용하는 것이 좋습니다.

deleteEvent: function(event) {
  this.events.splice(this.events.indexOf(event), 1);
}

또한 매개 변수를 사용하고 있으므로 this.event.

그러나 이런 식으로 indexOf모든 삭제에서 불필요한 것을 찾을 수 있습니다.이 문제를 해결하기 위해에서 index변수를 정의한 v-for다음 이벤트 객체 대신 전달할 수 있습니다.

그건:

v-for="(event, index) in events"
...

<button ... @click="deleteEvent(index)"

과:

deleteEvent: function(index) {
  this.events.splice(index, 1);
}


답변

. $ delete를 사용할 수도 있습니다.

remove (index) {
 this.$delete(this.finds, index)
}

출처 :


답변

속성 을 바인딩하는 것을 잊지 마십시오. 그렇지 않으면 항상 마지막 항목이 삭제됩니다.

배열에서 선택한 항목을 삭제하는 올바른 방법 :

주형

<div v-for="(item, index) in items" :key="item.id">
  <input v-model="item.value">
   <button @click="deleteItem(index)">
  delete
</button>

스크립트

deleteItem(index) {
  this.items.splice(index, 1); \\OR   this.$delete(this.items,index)
 \\both will do the same
}


답변

입력으로 할 때 더 재미 있습니다. 삽입 및 삭제 옵션을 사용하여 Vue2에서 수행하는 방법에 관심이 있다면 예제를 참조하십시오.

js 바이올린 좀 봐주세요

new Vue({
  el: '#app',
  data: {
    finds: []
  },
  methods: {
    addFind: function () {
      this.finds.push({ value: 'def' });
    },
    deleteFind: function (index) {
      console.log(index);
      console.log(this.finds);
      this.finds.splice(index, 1);
    }
  }
});
<script src="https://unpkg.com/vue@2.5.3/dist/vue.js"></script>
<div id="app">
  <h1>Finds</h1>
  <div v-for="(find, index) in finds">
    <input v-model="find.value">
    <button @click="deleteFind(index)">
      delete
    </button>
  </div>

  <button @click="addFind">
    New Find
  </button>

  <pre>{{ $data }}</pre>
</div>


답변

아이디를 통해 항목을 삭제할 수 있습니다.

<button @click="deleteEvent(event.id)">Delete</button>

JS 코드 내부

deleteEvent(id){
  this.events = this.events.filter((e)=>e.id !== id )
}

Vue는 관찰 된 배열의 변형 메서드를 래핑하여 뷰 업데이트도 트리거합니다. 자세한 내용을 보려면 여기클릭하십시오 .

이로 인해 Vue가 기존 DOM을 버리고 전체 목록을 다시 렌더링한다고 생각할 수 있습니다. 다행히도 그렇지 않습니다.


답변

<v-btn color="info" @click="eliminarTarea(item.id)">Eliminar</v-btn>

그리고 JS :

this.listaTareas = this.listaTareas.filter(i=>i.id != id)


답변

Splice는 특정 인덱스에서 요소를 제거하는 가장 좋은 방법입니다. 주어진 예제는 콘솔에서 테스트되었습니다.

card = [1, 2, 3, 4];
card.splice(1,1);  // [2]
card   // (3) [1, 3, 4]
splice(startingIndex, totalNumberOfElements)

startingIndex는 0부터 시작합니다.