【问题标题】:Vue js issues with passing event and index as parameterVue js 将事件和索引作为参数传递的问题
【发布时间】:2018-04-10 19:59:31
【问题描述】:

我正在尝试显示用户可以通过单击并上传新图像来更改的图像列表。第一个图像将是默认的添加图像。我在将索引和事件发送到方法时遇到问题。如果我在 html 中显示照片的索引,那是正确的。但是,如果我将索引作为参数发送给方法,它总是 0。换句话说,我使用 {{index}} 会产生正确的索引,但我使用 console.log(index) 会产生 0。一些建议。谢谢!

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

【问题讨论】:

    标签: vue.js vuejs2


    【解决方案1】:

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

    <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);
        //...
       }
    

    【讨论】:

      猜你喜欢
      • 2020-07-27
      • 2018-08-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-25
      • 1970-01-01
      • 2010-10-04
      相关资源
      最近更新 更多