Preview multiple images while uploading with V-for in Vue JS

Having trouble displaying images in a loop using :ref

I've implemented FileReader() to read the field.

Vue Component

<div v-for="(image, index) in imgFile" :key="index">
<img :ref="'image'+parseInt( index )">
{{image.name}}
</div>
<input type="file" class="file-upload-default" @change="onFileChange" multiple>
<span style="cursor:pointer" class="file-upload-browse">
<img src="/addmore.png" height="50" width="50">
</span>

export default{
onFileChange(e){
var selectedFiles = e.target.files;
for (var i=0; i < selectedFiles.length; i++){
  this.imgFile.push(selectedFiles[i]);
}

if (selectedFiles) {
  for (var i=0; i < this.imgFile.length; i++){
    let reader = new FileReader();
    reader.addEventListener('load', function(){          
     this.$ref["image"+parseInt( i )][0].src = reader.result;         
   }.bind(this), false); 
     reader.readAsDataURL(this.imgFile[i]);
   }
     }
   }
 }

My goal is to display the selected images from the event listener.

Answer №1

Enhance the structure of your architecture by dividing your logic into two separate components. Here is an example of how you can achieve this:

<template>
  <div class="parent-component">
    <image-component :image="image" v-for="(image, index) in images" :key="index" />
  </div>
</template>

<script>
export default {
  name: 'ParentComponent',
  data () {
    return {
      images: []
    };
  }
};
</script>
<template>
  <div class="image-component">
    <img ref="imgElement">
    {{ image.name }}
  </div>
</template>

<script>
export default {
  name: 'ChildComponent',
  props: {
    image: {
      type: Object,
      required: true
    }
  },
  methods: {
    ...
  },
  mounted () {
    // The loop is not necessary here because each instance of the image-component only contains one <img> element. The looping logic is handled in the parent component.
    console.log(this.$refs.imgElement);
  }
};
</script>

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

Is it possible to update labels on an AngularJS slider using a timeout function?

I recently started implementing an AngularJS slider to navigate through various date and time points. Specifically, I am utilizing the draggable range feature demonstrated in this example - https://jsfiddle.net/ValentinH/954eve2L/ The backend provides the ...

A straightforward redirection in Express involving a static file

Just starting out with Node and Express and encountering a bit of trouble. I have a static html page where users enter their username via ajax to my server, and then I want to redirect them to another html file. const express = require("express"); const b ...

This error is thrown when trying to access the property 'message' of an undefined value

I'm currently working on adding an AJAX contact form to my website. However, I've run into a problem where when I try to submit the form, I encounter the following error in Google Chrome: "Uncaught TypeError: Cannot read property 'message&a ...

Is Material-UI suitable for a large-scale enterprise application?

We are in the process of transforming a massive and outdated MVC Java EE application into React. This particular application consists of a browser-based user interface with an extensive range of views that include intricate forms, listings, and links. It i ...

Discover additional information using just the ID

I am developing a simple app and facing an issue with extracting information from furnitures.js: export default [ { id: 1, name: 'Sofa Sydney', dim1: '2.25m', dim2: '1.45m x 1.95m'}, { id: 2, name: 'Sofa Alex&apos ...

Unable to find the solution for 'material-ui/Button'

I recently encountered an issue while trying to integrate the material-ui library into my existing React project. I used the command npm install --save material-ui, but it resulted in an error upon running it. The error message received is as follows: ...

Utilize jQuery's .append() function to dynamically insert content into your webpage

I currently have tab elements set up like this: <div class="tab-pane fade active in" id="tab-a"> </div> To populate the content of that tab with a JavaScript string array, I am using the following code snippet: var full_list = ""; for (var ...

Creating Browser Extensions with Vue.js and Vue CLI

I am in the process of creating a Chrome Extension with a frontend powered by Vue.js. Everything was going smoothly using vuecli until my app started utilizing the Webextension-API. This API is only accessible to registered Extensions, not normal websites. ...

Traversing JSON Data using Vanilla JavaScript to dynamically fill a specified amount of articles in an HTML page

Here is the code along with my explanation and questions: I'm utilizing myjson.com to create 12 'results'. These results represent 12 clients, each with different sets of data. For instance, Client 1: First Name - James, Address - 1234 Ma ...

Retrieve the row id from the table by clicking on a button in a modal box using jQuery

I am encountering a challenge with a small task due to my limited experience in jQuery. I have a table where each row has an icon. When the icon is clicked, a modal box appears with some content. After closing the modal box, I want to retrieve the table ro ...

What is the best way to add both the id and the full object to an array list at the

Requirements: "admin-on-rest": "^1.3.3", "base64-js": "^1.2.1", "react": "^16.2.0", "react-dom": "^16.2.0" I have a User model that includes a List of Roles. // User { id: "abcd1234", name: "John Doe", ... authorities: [ { ...

Creating dynamic styles with Material-UI's useStyles

Attempting to implement the same logic using material-ui's useStyle feature <div className={'container ' + (state.unlocked ? 'containerUnlocked' : '')}> I thought it might look like this: <div className={`${clas ...

Being required to design a distinct div for every article I am extracting from the API

In the midst of developing a website for my college project, I have successfully configured my news API to pull and display data using JavaScript. Currently, I am faced with the challenge of having to create separate div elements each time I want to add n ...

Include the <component> tag within a Vue.js template

Recently, I embarked on a journey to learn Vuejs and stumbled upon a single file component that has left me puzzled: <template> <component :is="user === undefined ? 'div' : 'card'"> ...some code </ ...

Using Express and Node.js to display a page populated with information

On my webpage, I currently have a list of Teams displayed as clickable links. When a link for a specific Team is clicked, the Key associated with that Team is extracted and sent to the /team/:key route to retrieve the respective data. If the data retrieval ...

"Discover the step-by-step process of transforming an input field value into a checkbox with

I've been experimenting with creating a To-Do list using HTML, CSS, and Javascript. I've managed to capture the input field value in a fieldset so far. However, my goal is to find a way to transform the input field value from the textfield into a ...

Efficiently Encoding Still Image Data for NextJS

Currently, I am experimenting with a completely static method in my new Next.js v12 project. I am creating 5-6 data files to use with getStaticProps. Here is an example of one of the data file structures (they are all similar): import SqAshland1 from &apos ...

I am uncertain about how to interpret this method signature

Can you help me determine the correct method signature for handleError? The linter tslint is indicating an error message that says expected call-signature: 'handleError' to have a typedef (typedef). Here is the code snippet in question: import ...

What steps can I take to prevent the user from clicking on a different edit button for another row?

Is there a way to prevent users from clicking the edit button in another row before they have saved their changes? I want users to click the save button before editing another row. How can I reset the textbox to its original form or remove it altogether ...

Eliminate event listener using unique identifier

Is there a way to retrieve information about all event handlers for an element in JavaScript? $._data($('#element_id')[0], "events"); This will provide a detailed record of every event handler attached to the element. 0: {type: "c ...