I've been stuck on this seemingly simple problem for hours.
I developed an app that allows users to add or remove files for upload.
However, whenever I click the delete button, it always removes the last item. I tried adding :key="key"
, but it didn't make a difference.
What could be wrong with my code? Here is the link to the CodePen: 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);
}
}
}
},
});