Skip to content
Advertisement

sending extra argument to event handler with event argument

i have this input with onchange event handler

  <input accept="image/*" type='file' id="imgInp" @change="imageChange" />

my imageChange method is like

  methods : {
   imageChange(e ){
      const file = e.target.files[0];
      console.log(file);
      URL.createObjectURL(file);
      this.model.image = URL.createObjectURL(file);

     } , 

  }  

basically setting model.image value on change now i want to have multiple images on my model … so i want to change the image property to array and have an input for each image

<div v-for="(image , index) in model.images" v-bind:key="index">
  <input accept="image/*" type='file' id="imgInp" @change="imageChange" />
</div>

now i need to send the imaeg index in the array to my function as well so i can replace that index image like

and change my method to

  imageChange(e , index ){
      console.log(`event ->`);
      console.log(e);
      console.log(`index ->`);
      console.log(index);
      //URL...
      this.model.images[index] = URL.createObjectURL(file);
  } 

but this will result in undefined event here is the output

event ->
undefined
index ->
0

how can i send extra argument to event handler without losing event argument ?

Advertisement

Answer

Just execute the function inside with @change event, and pass the Vue provided $event params first then index param.

<div v-for="(image , index) in model.images" v-bind:key="index">
  <input accept="image/*" type='file' id="imgInp" @change="imageChange($event, index)" />
</div>
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement