itsource

Vue.js 어레이에서 항목을 삭제하는 방법

mycopycode 2022. 8. 27. 10:19
반응형

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

});

이벤트를 함수에 전달하려고 했는데, 슬라이스 기능이 있는 이벤트를 삭제하는 것보다 어레이에서 데이터를 삭제하는 코드라고 생각했습니다.심플한 버튼과 클릭 이벤트를 사용하여 어레이에서 데이터를 삭제하는 가장 깔끔한 방법은 무엇입니까?

사용하고 있다splice잘못된 방법으로.

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

array.splice(시작)

array.splice(시작, delete Count)

array.splice(시작, deleteCount, itemForInsertAfterDeletion1, itemForInsertAfterDeletion2, ...)

시작은 제거할 요소가 아니라 시작할 인덱스를 의미합니다.두 번째 매개 변수를 전달해야 합니다.deleteCount즉, "인덱스 {start}에서 시작하는 요소 1개를 삭제합니다."

그러니 다음 방법을 택하는 것이 좋습니다.

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

또한 파라미터를 사용하고 있기 때문에 직접 액세스 할 수 있습니다. this.event.

하지만 이 방법으로 당신은 불필요한 것을 찾을 것이다.indexOf삭제할 때마다 이 문제를 해결하기 위해index변수 at yourv-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에서 삽입 및 삭제 옵션을 사용하여 수행하는 방법에 관심이 있는 경우 예를 참조하십시오.

한번 봐주세요.

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>

ID를 통해 항목을 삭제할 수 있습니다.

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

JS 코드 내부

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

Vue는 관찰된 어레이의 변환 메서드를 래핑하여 보기 업데이트도 트리거합니다.자세한 내용은 여기를 클릭해 주세요.

이로 인해 Vue가 기존 DOM을 폐기하고 목록 전체를 다시 렌더링할 것이라고 생각할 수 있습니다.다행히 그렇지 않습니다.

다음과 같은 방법을 모두 생략하면 어떨까요?

v-for="(event, index) in events"
...
<button ... @click="$delete(events, index)">
<v-btn color="info" @click="eliminarTarea(item.id)">Eliminar</v-btn>

JS의 경우:

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

스플라이스는 특정 인덱스에서 요소를 제거하는 데 가장 적합합니다.이 예는 콘솔에서 테스트됩니다.

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

startingIndex는 0부터 시작합니다.

언급URL : https://stackoverflow.com/questions/43046332/how-to-remove-an-item-from-an-array-in-vue-js

반응형