簡體   English   中英

splice 總是刪除 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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM