programing

Vue array.splice 목록에서 잘못된 항목 제거

prostudy 2022. 7. 17. 17:45
반응형

Vue array.splice 목록에서 잘못된 항목 제거

리스트가 있고, 그것을 루프하기 위해 for 루프를 사용하고 있습니다.구조는 다음과 같습니다.

salesLists: { 
  1: [ [], [], [] ]
  2: [ [], [] ]
}

html:

<div v-for="(saleLists, index) in salesLists">
    <my-comp v-for="(item, i) in saleLists" :key="i" :index="parseInt(i)+1"></my-comp>
</div>

이제 아이템을 삭제하려고 합니다.salesLists[1]배열. 그 버튼을 가지고 있고@click="removeForm":

removeForm(e) {
        var index = parseInt(e.target.getAttribute('data-index')) - 1 // = 2
        var client = e.target.getAttribute('data-client')             // = 1
        //Vue.delete(this.salesLists[client], index);
        this.salesLists[client].splice(index, 1)
        this.$forceUpdate()
}

단, 키를 지정하지 않고 빈 어레이이기 때문에 DOM에서 적절한 요소를 삭제하지 않습니다.2의 인덱스를 삭제합니다만, 현재 상태 그대로입니다.v-for항목을 반복하여 개수를 줄이면 마지막 항목만 제거됩니다.

이 문제를 해결하는 적절한 방법은 무엇입니까?:/

여기 Fielle이 있습니다.https://jsfiddle.net/8rvfz40n/ 각 입력 필드에 다른 값을 입력하고 가운데 값을 삭제해 보십시오.마지막 값이 삭제됩니다.

<div v-for="(saleLists, index) in salesLists">
    <my-comp v-for="(item, i) in saleLists" :key="i" :index="parseInt(i)+1"></my-comp>
</div>

인덱스를 키로 사용하는 것이 문제입니다. 중간에 있는 항목을 삭제하면 손실된 인덱스가 마지막이 됩니다.

제 경우 ID와 같은 항목에 고유한 "해시"를 추가하는 솔루션을 찾았는데, 항목이 뉴스일 경우 ID는 null입니다.

사용하는 해시는 타임스탬프입니다.

Hash: new Date().getTime()

그 후:

 <div v-for="(saleLists, index) in salesLists">
     <my-comp v-for="(item, i) in saleLists" :key="item.Hash" :index="parseInt(i)+1"></my-comp>
 </div>

이건 많은 사람들을 혼란스럽게 만들어요

이에 대한 답변은 얼마 전 vue 포럼(https://forum.vuejs.org/t/solved-array-of-components-wrong-after-element-remove/11866/3)에서 작성했습니다.

그래서 문제는 이것이다.

어레이 [rec1, rec2, rec3]가 있습니다.

해당 어레이의 키는 0, 1, 2 입니다.

인덱스 1에서 항목을 제거하면 값이 [rec1, rec3]인 배열을 얻을 수 있지만, 배열을 삭제해도 인덱스를 건너뛰지 않기 때문에 키는 [0, 1]이 됩니다.템플릿에서 키를 그리면 키가 정의되어 있지 않기 때문에 컴포넌트에 표시되는 변경은 키 또는 인덱스2가 없어지기 때문에 마지막 항목이 삭제됩니다.

그것을 해결하려면 , 당신이 의도한 아이템을 목표로 하고 있는지 확인할 다른 방법을 찾을 필요가 있다.

https://jsfiddle.net/8rvfz40n/2/

고객님의 경우 아이템 사용list지수 대신i원하는 항목을 제거합니다.

<div id="app">
  <div v-for="lists in xLists">
    <my-comp v-for="(list, i) in lists" :list="list"></my-comp>
  </div>
</div>

또 다른 대안은 어레이 내부에 고유의 키를 저장하는 것이지만, 아시다시피 이 키를 유지하는 것이 더 어려울 수 있습니다.

문제는 매우 간단합니다.에서 오브젝트 키에 대한 참조가 손실됩니다.xLists첫 번째 루프에서요.오브젝트 키를 저장하고 소품으로 전달하면 해당 참조가 유지됩니다.

<div v-for="(saleLists, index) in salesLists">
    <!-- index will refer to the object key -->
    <my-comp v-for="(item, i) in saleLists" :key="i" :index="i+1" :sales-list-index=":index"></my-comp>
</div>

소품만 .salesListIndex이 키를 사용하여 오브젝트 내의 올바른 중첩 배열을 가리킵니다.실제 예제의 컴포넌트가 어떻게 기술되어 있는지는 명확하지 않지만, 바이올린을 참조하고 있습니다(객체 키인지 어레이 키인지 알 수 있도록 알파벳 키를 사용했습니다만, 실장 면에서는 동일합니다).

Vue.component('my-comp', {
  props: ['index', 'value', 'listKey'],
  template: `
  	<div>
    	<p>xListsKey: {{ listKey }}, index: {{ index }}</p>
    	<input :value="value" /> 
      <button :data-index="index" @click="remove">del </button>
    </div>
  `,

  methods: {
    remove(e) {
      var index = e.target.getAttribute('data-index');
      this.$parent.xLists[this.listKey].splice(index, 1)
    }
  }
})

new Vue({
  el: '#app',
  data: {
    xLists: {
      'aa': [
        ['lorem'],
        ['ipsum'],
        ['dolor']
      ],
      'bb': [
        ['foo'],
        ['bar']
      ]
    }
  }
})
<script src="https://unpkg.com/vue"></script>

<div id="app">
  <div v-for="(lists, listKey) in xLists" :key="listKey">
    <my-comp v-for="(list, i) in lists" :key="i" :index="i" :value="list" :list-key="listKey"></my-comp>
  </div>
</div>

언급URL : https://stackoverflow.com/questions/45655090/vue-array-splice-removing-wrong-item-from-list

반응형