0

I am trying to display a list of images that users can change by clicking and uploading a new image. The first image is going to be a default add image. I am having issues sending both and index and an event to a method. If I display the index of the photo in the html, it is correct. But, if I send the index to the method as a parameter, it is always 0. In other words, my use of {{index}} produces the correct index, but my use of console.log(index) produces 0. Looking for some advice. Thanks!

html:

<v-layout v-bind="binding">
     <v-flex v-for="(image, index) in imageData">
       <v-card  style="margin:10%;">
         {{index}}
         <label for="imgload">
           <v-card-media :src="image" v-if="imageData.length > 0"></v-card-media>
         </label>
         <input hidden id="imgload" type="file" @change="previewImage($event, index)" accept="image/*">
       </v-card>
     </v-flex>
   </v-layout>

method:

previewImage: function(event, index) {
     this.toggle="false";
     var input = event.target;
     if (input.files && input.files[0]) {
         var reader = new FileReader();
         reader.onload = (e) => {
           console.log(index);
           if (index == 0) {
             this.imageData.push(e.target.result);
           } else {
            this.imageData[index] = e.target.result;
           }
         }
         reader.readAsDataURL(input.files[0]);
     }
   },

1 Answer 1

2

As a workaround, you can pass index as a data attribute instead,

<input hidden id="imgload" type="file" @change="previewImage($event)" accept="image/*" :data-index="index">

and in your method, get the index using event.target.dataset.index

previewImage: function(event) {
    const index = event.target.dataset.index;
    //...

           console.log(index);
    //...
   }
Sign up to request clarification or add additional context in comments.

1 Comment

Does anyone know why this workaround is needed? I had the same issue

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.