I am currently utilizing VueJs to upload multiple images. I am saving their respective base64 values in an Array to store them in the database. I have also added a remove feature, so when the user clicks on the remove button, it finds the index of that element and removes it from the array.
Although the clicked image value is successfully removed from the array, the position of the images does not change visually. It appears as if only the last image is deleted. How can I both remove the value of the image from the Array and remove the corresponding image from the UI?
To view the code, click here: https://codepen.io/echobinod/pen/GVMOqJ
<div id="app">
<input type="file" multiple @change="onFileChange" /><br><br>
<div class="row">
<div v-for="(image, key) in images">
<div class="col-md-4" :id="key">
<button type="button" @click="removeImage(key)">
×
</button>
<img class="preview img-thumbnail" v-bind:ref="'image' +parseInt( key )" />
{{ image.name }}
</div>
</div>
</div>
</div>
<script>
const vm = new Vue({
el: '#app',
data() {
return {
images: [],
}
},
methods: {
onFileChange(e) {
var selectedFiles = e.target.files;
for (let i=0; i < selectedFiles.length; i++)
{
this.images.push(selectedFiles[i]);
}
for (let i=0; i<this.images.length; i++)
{
let reader = new FileReader(); // instantiate a new file reader
reader.addEventListener('load', function(){
this.$refs['image' + parseInt( i )][0].src = reader.result;
}.bind(this), false);
reader.readAsDataURL(this.images[i]);
}
},
removeImage (i) {
var arrayImages = this.images;
var index = arrayImages.indexOf(arrayImages[i]);
arrayImages.splice(index, i);
}
})
</script>