Vue js 将事件和索引作为参数传递的问题 [英] Vue js issues with passing event and index as parameter

查看:25
本文介绍了Vue js 将事件和索引作为参数传递的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试显示用户可以通过单击并上传新图像来更改的图像列表.第一张图片将是默认的添加图片.我在将索引和事件发送到方法时遇到问题.如果我在html中显示照片的索引,它是正确的.但是,如果我将索引作为参数发送给方法,则它始终为 0.换句话说,我使用 {{index}} 会产生正确的索引,但我使用 console.log(index) 会产生 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>

方法:

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]);
     }
   },

推荐答案

作为一种解决方法,您可以将索引作为数据属性传递,

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">

在你的方法中,使用 event.target.dataset.index

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

           console.log(index);
    //...
   }

这篇关于Vue js 将事件和索引作为参数传递的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆