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

ES6 Set enables the storage of multiple occurrences of arrays and objects within

Review the script below. I'm currently testing it on Chrome. /*create a new set*/ var items = new Set() /*add an array by declaring its type as an array*/ var arr = [1,2,3,4]; items.add(arr); /*display items*/ console.log(items); // Set {[1, 2, 3, ...

Managing VueJS components and Observers during the rendering process to ensure smooth functionality in a multi-phase environment

Situation: As part of my development work, I am creating a Vue scroll component that encompasses a variable number of HTML sections. This component dynamically generates vertical page navigation, allowing users to either scroll or jump to specific page lo ...

Initiating an Ajax POST request when the onblur() event is triggered

Having an issue with Ajax. I'm trying to submit a changed value from an input field on the onblur() event, but there's a flicker that's bothering me. When I enter a new value and click away, the old value briefly flashes back before changi ...

Struggling to Confirm Inaccuracies in Material UI Forms

Struggling to validate form errors in React with Material UI using JOI and running into issues. Even the console.log() results are not showing up in my validate function. The error display is also confusing. ... import React from "react"; import ...

Explore the capabilities of Chart JS integration using Python Selenium

I've been attempting to click the buttons on this Chart JS located on the webpage . Despite trying by xpath, full xpath, and JS path, I have not been successful. An example of my attempt to press the "All" button can be seen below: Thank you! from se ...

Ending a timer from a different function in a React component

Currently, I am delving into the world of React and attempting to create a timer component. While I have successfully implemented the start function for my timer, I am now faced with the challenge of stopping the timer using an onclick handler from another ...

Clicking on a JQuery dropdown menu will always result in it staying open

After creating a dropdown menu click, I noticed some strange behavior. When I click the dropdown button, the menu appears as expected. However, if I move my cursor away without clicking the button again, the dropdown menu disappears and behaves like a hove ...

Unique 512-character string generated with Node.js

Is it possible to create a string of 512 characters in length that is truly unique? Can the nodejs built-in crypto module be used for this purpose to minimize collisions? Do you think the following sample code can achieve this goal? crypto.randomBytes(51 ...

How can I set a background image to automatically adjust to the width of the window, be full height, allow for vertical scrolling, and

How can I set a full-screen background image that adjusts to the body width without horizontal scrolling, maintains height proportionate to width, and allows for vertical scrolling? Here is my current code: html, body { margin: 0px; padding: 0px; } bo ...

retrieving JSON data using ajax and processing it in PHP

I have some data that needs to be sent to the backend, and it looks like this: function view(){ let id = "12345678"; let profile = [{name:"dave", department : "Engineering"}, {name:"Tedd", ...

What criteria should I use to determine if a post has been favorited by a user using Mongoose?

Creating a function for users to like posts has been my recent project. Each post is stored as an object in my MongoDB collection with a specific schema. { title: String, text: String } On the other hand, users have their own unique schema as well. ...

Obtain the key's name from the select query

My task is to populate a select element from JSON data, but the challenge lies in the formatting of the JSON where the keys contain important information. I do not have control over how the data is structured. I am attempting to iterate through the JSON a ...

Using JavaScript to display content on the screen

As a newcomer to Javascript, I'm looking for a way to display my variable on the webpage without utilizing <span> or innerHTML. var pProductCode = $('[name=pProductCode]').val(); $('input[id*="_IP/PA_N_"]').each(function(i){ ...

Transferring parameters via URL - When passing single quotes, they are converted to &#39;

In my current ASP.NET project, we encounter an issue with passing parameters through the URL. Whenever a single quote is passed, the URL automatically changes all single quotes to %27 and the actual JavaScript value reads them as &#39; I need assistan ...

Execute PHP script through jQuery request within the context of a Wordpress environment

I want to replicate a specific functionality in WordPress. In this functionality, jQuery calls a PHP file that queries a MySQL table and returns the result encapsulated within an HTML tag. How can I achieve this? <html> <head> <script ...

Utilize three.js to set the camera's position and rotation

In my current setup, I have a particular object in view using a PerspectiveCamera. By utilizing OrbitControls, I can navigate around the object, rotate it, pan it, and more. My goal is to reposition the object to a specific location at a specific angle an ...

The callback function is not responding properly in my HTTP POST request

I'm currently working with some code that involves callbacks: function getUserToken(data, callback) { var password_sha256 = sha256(data.password); getAppById(data.app_id).then(function(res) { console.log("app"+res); if (!r ...

Add design to the footer during a specific event using Javascript

Here is the CSS code I am working with: .footer { font-family: "lato", sans-serif; padding: 20px; line-height: 1.2; text-align: right; background: #eee; color: #0D47A1; font-size: 13px; height: 80px; position: fixed; right: 0px; botto ...

Using JavaScript to display dynamic data pulled from Django models

I am currently in the process of designing my own personal blog template, but I have encountered a roadblock when it comes to creating a page that displays previews of all posts. This particular page consists of two columns, #content-column-left and #conte ...

Can you explain the purpose of CLOUDINARY_DEFAULT_URL and CLOUDINARY_DEFAULT_PUBLICID to me?

Need help with my user sign up page Here is my .env file This is my signup controller code: const User = require('../model/User'); const bcrypt = require('bcrypt'); const { uploadToCloudinary } = require('../utils/cloudinary&apos ...