拼接总是删除 Vue.js 中的最后一项

splice always delete last item in Vue.js

我确定问题很简单,但我已经堆了几个小时了。

我创建了一个可以添加或删除上传文件的应用程序。

当我点击删除按钮时,它总是删除最后的项目。 我试图通过添加 :key="key" 来解决它,但它没有任何改变。

我的代码可能有什么问题? 这是代码笔: https://codepen.io/shanyulin/pen/RwaWaZy?editors=1010

HTML

<div id="app">
  <div class="form-group clearfix" v-for="(event, key) in events" v-bind:key="key">
  <input name="attachment[]" accept="image/png, image/jpeg, application/pdf" type="file" class="form-control form-control-lg">
  <button @click="deleteEvent(key)" class="btn btn-danger">x</button>
</div>
<button @click="addEvent" class="btn btn-dark">+</button>
</div>

Js

const app = new Vue({
    el: '#app',
    data() {
        return {
            events: [{}],
           }
    },
    methods: {
        addEvent: function() {
            let quantity = this.events.length;
            if (quantity < 6) {
                this.events.push({
                    index: ''
                });
            } else {
                return false;
            }
        },
        deleteEvent: function(key) {
            let quantity = this.events.length;
            if (quantity == 1) {
                alert("Please upload at least one file.");
            }
            if (quantity > 1) {
                const confirmed = confirm("Do you really want to delete?");
                if (confirmed) {
                    this.events.splice(key, 1);
                }
            }
        }
    },
});

key 的数组索引不可靠。如果您有一个包含三个元素的数组,则键为 0,1,2。当您删除第二个时,键是 0,1,而不是 0,2

您需要为每个元素提供唯一键。

const app = new Vue({
    el: '#app',
    data() {
        return {
            events: [{}],
            uniqueKey: 0,
           }
    },
    methods: {
        addEvent: function() {
            let quantity = this.events.length;
            if (quantity < 6) {
                this.events.push({
                    index: '',
                    key: this.uniqueKey++
                });
            } else {
                return false;
            }
        },
        deleteEvent: function(key) {
            let quantity = this.events.length;
            if (quantity == 1) {
                alert("Please upload at least one file.");
            }
            if (quantity > 1) {
                const confirmed = confirm("Do you really want to delete?");
                if (confirmed) {
                    this.events.splice(key, 1);
                }
            }
        }
    },
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <div class="form-group clearfix" v-for="(event, key) in events" v-bind:key="event.key">
  <input name="attachment[]" accept="image/png, image/jpeg, application/pdf" type="file" class="form-control form-control-lg">
  <button @click="deleteEvent(key)" class="btn btn-danger">x</button>
</div>
<button @click="addEvent" class="btn btn-dark">+</button>
</div>