Tips for deleting multiple uploaded images from an array using Vue.Js and updating the UI accordingly

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)">
            &times;
        </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>

Answer №1

If you want the component to reload and see changes in the UI, simply updating the data may not be enough. One effective way to force a reload is by adding a key to the element that needs to be reloaded, as demonstrated in this code snippet:

<div v-for="(image, key) in images" :key="reloadKey">
...
data(){
  return {
    reloadKey: 0}}
...
removeImage (i) { 
        var arrayImages = this.images;

        var index = arrayImages.indexOf(arrayImages[i]);

          arrayImages.splice(index, i);
this.reloadKey++
    }
  }

For more detailed information on how to force a re-render, check out:

Answer №2

One of the great advantages of utilizing Vuejs is its seamless two-way data binding capability between the DOM and your data model. This means that any modifications made to the 'images' array in the 'data' section will automatically be reflected in the user interface.

To quickly resolve this issue, simply populate the 'arrayImages' array and then set 'this.images = arrayImages', allowing the UI to update accordingly.

Answer №3

Consider utilizing,

arrayPhotos.slice(position, 1);

as opposed to employing i in the slice method

arrayPictures.slice(position, i);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What could be the reason for my image not loading properly in Vue.js 3?

I'm struggling to load an image using a relative path and value binding with v-for in my template code. Despite following the correct syntax, the website is displaying an error indicating that it can't retrieve the image. Here's a snippet of ...

Can all actions in the ofType operator be waited for before calling next?

I have a list of dynamic redux actions that I need to monitor in order to trigger another action in my epic once all of them have been called. The key here is that the actions within this list can change and are not fixed. It would be ideal if the ofType o ...

Encountering HTML content error when attempting to log in with REST API through Express on Postman

I'm currently in the process of developing a basic login API using Node.js and Express. However, I've encountered an error when testing with Postman: <!DOCTYPE html> <html lang="en"> <head> <meta charse ...

To search for specific data in a Mongoose schema by specifying an attribute of type ObjectId

Here are the schemas I am working with: UserLike const UserLikeSchema = Schema({ user: { type: Schema.Types.ObjectId, ref: "User", required: [true, "User is required"], }, game: { type: Schema.Types.ObjectId, ...

Javascript code that enables me to specify the type of weather

My intention with this code was to create unique characteristics for different weather types and randomly select one by generating a random number. I defined 11 different weather types as objects of the Weather class. I then implemented a getWeather funct ...

inserting a dynamic variable into a JSON string

My goal is to create a javascript object, var systemName = {"system" : varA}; However, I want the object to be structured like `{"system" :"varA"} where varA contains the variable value but is enclosed in double quotes. I attempted {"system" : "'+ ...

The function 'downloadFunc' is not recognized as a valid function within the context of ReactJS custom hooks

Here is a unique custom hook that triggers when the user presses a button, calling an endpoint to download files as a .zip: import { useQuery } from 'react-query'; import { basePath } from '../../config/basePath'; async function downlo ...

Jest does not recognize AnimationEvent as a defined element

I am currently facing an issue while attempting to simulate an animationEvent for a test within my Angular application. The error message I receive is: ReferenceError: AnimationEvent is not defined. Given that this feature is experimental, it seems like ...

How can multiple buttons be added to each row in Jquery datatables and how can events be applied to them?

I currently have one button, but I am in need of two buttons. These buttons will trigger MySql commands when clicked to retrieve data from the database. How can I set up an event handler for these buttons? $(document).ready(function () { var table= ...

Utilizing withRouter outside a component to navigate through historical data

I'm still getting the hang of react router and encountering some challenges. I can easily use history within a component without any issues. However, when trying to access history from a function outside the component, I run into problems. Despite my ...

Exploring Next.js Font Styling and Utilizing CSS Variables

I'm attempting to implement the "next" method for adding fonts, but I find the process described quite complex just to preload a font. I experimented with exporting a function to create the font and then using a variable tag to generate a CSS variabl ...

Node.js Express.js Module for Asynchronous SqLite Operations

Currently, I am working on a task that involves making synchronous requests to a database and passing the data to Express. Here is the code snippet: app.get('/', (req, res) => { let db = new sqlite3.Database('./Problems.db'); ...

Is there a way to delete highlighted text without using execCommand and changing the font color

With my current use of JavaScript, I am able to highlight or bold a selected text range successfully. However, I am unsure how to undo the bold and unhighlight the text if the button is clicked again and the selected range is already bolded or highlighted. ...

failure of text to display in d3.append

Having trouble displaying a tooltip on a rectangle in d3js. The tooltip renders, but the text doesn't show up. After researching similar issues, I discovered that I cannot directly append 'text' to a 'rect' element. I tried addin ...

What is the method to ensure that the Node REPL solely displays the result?

Is there a way to execute a script in Electron that only logs the output value without displaying all the code? I am utilizing xterm.js and node-pty for this project. For instance, consider the following sample code: // Add your code here function multi ...

unable to retrieve the response from a POST request sent to a node server

Currently in the process of learning how to utilize node and express, I have embarked on creating a sample website that incorporates both along with the Google translate API. The goal is to explore the numerous features offered by these technologies. Unfor ...

I am currently attempting to generate a chart that displays information on countries utilizing the restcountries API. Despite being a beginner in this area, I have encountered some challenges and am seeking guidance

I'm struggling to display detailed information for each country separately. Whenever I try to loop through the data, all the contents end up getting merged into a single cell. What can I do to achieve the desired result? https://i.stack.imgur.com/dZS ...

How to toggle the visibility of specific div elements within a v-for loop depending on their content?

I am working on a scenario where I have a collection of objects displayed in a v-for loop. Each object has a specific key value pair, and I want the user to be able to toggle a button outside the loop to show or hide elements based on that key value. Initi ...

Using TypeScript: Implementing array mapping with an ES6 Map

If I have an array of key-value objects like this: const data = [ {key: "object1", value: "data1"}, {key: "object2", value: "data2"}, {key: "object3", value: "data3"}, ] const mappedData = data.map(x => [x.key, x.value]); const ES6Map = n ...

What is the process for creating a pop-up bubble that appears when the cursor hovers over an image displayed within a table using R Shiny?

I am currently working on code that is almost achieving my desired functionality. I want to make it so that hovering over each question mark in the table will trigger a pop-up bubble displaying the help text, rather than having the text appear at the botto ...