programing

하위 구성 요소(행)를 제거하는 예기치 않은 동작

prostudy 2022. 3. 30. 00:09
반응형

하위 구성 요소(행)를 제거하는 예기치 않은 동작

설명:

몇 가지 제품이 있는 테이블이 있는데 각 행은 사용자 지정 vue입니다.<row>구성 요소

각 요소에는 사용자 정의 "제거" 이벤트를 트리거하는 닫기(제거) 버튼이 있다.기본 앱이 이 이벤트를 듣고 하위 항목(인덱스별)을 제거함

일부 정적 텍스트의 한 부분 행에 숫자가 포함된 입력이 들어 있는 경우.

문제:

상위(Vue app)는 행을 제거하지만, 입력 값이 다음 행의 입력으로 이동(그리고 이전 값을 대체)된다.

예상 동작:

일단 텍스트 입력 값이 제거되면 상관없는 항목을 간단히 제거하고 싶다.그것은 그 가치를 다음 형제자매로 옮겨서는 안 된다.

예를 첨부한다.

let row = Vue.component('row', {
  name: 'row',
  props: ['number', 'name', 'sq'],
  data: () => ({
    quantity: 0
  }),
  template: '<tr>' +
    '<td>{{number}}</td>' +
    '<td>{{name}}</td>' +
    '<td><button v-on:click="quantity--">-</button><input type="text" :value="quantity"><button v-on:click="quantity++">+</button></td>' +
    '<td><button v-on:click="remove">&times;</button></td>' +
    '</tr>',
  methods: {
    remove: function() {
      this.$emit('remove', this.quantity)
    }
  },
  beforeMount() {
    this.quantity = this.sq
  }

})


new Vue({
  el: "#app",
  data: {
    out: [],
    rows: [{
        name: "Icecream",
        sq: 0
      },
      {
        name: "Sugar cube",
        sq: 50
      },
      {
        name: "Peanut butter",
        sq: 0
      },
      {
        name: "Heavy cream",
        sq: 0
      },
      {
        name: "Cramberry juice",
        sq: 0
      }
    ]
  },
  methods: {
    removeRow: function(index, quantity) {
      this.out.push(`Removing row ${index} (${this.rows[index].name} | ${quantity} units)`)
      this.rows.splice(index, 1)
    }
  },
  computed: {
    log: function() {
      return this.out.join("\r\n")
    }
  }
})
body {
  background: #20262E;
  padding: 20px;
  font-family: Helvetica;
}

h2 {
  font-weight: bold;
  margin-bottom: 10px;
}

#app {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  transition: all 0.2s;
}

td {
  padding: 4px 5px;
}

input {
  width: 40px;
  text-align: center;
}

h4 {
  margin-top: 20px;
  margin-bottom: 5px;
}

#log {
  padding: 10px;
  background: #20262E;
  color: #fff;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.min.js"></script>
<div id="app">
  <h2>Cart:</h2>
  <table>
    <row v-for="(row, index) in rows" :number="index" :name="row.name" :sq="row.sq" v-on:remove="removeRow(index, $event)"></row>
  </table>

  <h4>Log</h4>
  <pre id="log" v-html="log"></pre>
</div>

@Bert가 논평에서 언급했듯이.문제는 내가 열쇠를 잃어버렸다는 것이었다.

https://vuejs.org/v2/api/#key

덧붙여서 문제를 해결했다. 고마워

참조URL: https://stackoverflow.com/questions/51445758/unexpected-behaviour-removing-a-child-component-row

반응형