v-model on input type files vue.js

brycode picture brycode · Feb 2, 2018 · Viewed 9.8k times · Source

How to take data from v-model array in input type="file" multiple ?

<input type="file" multiple v-model="modFiles[index]">
<input type="file" multiple v-model="modFiles[index]">
<input type="file" multiple v-model="modFiles[index]">

I'm using v-for loop and I can get the first data from each modFiles[].

this.modFiles[0] //take the first from multiple file

But it's only the first data. How can I take all the data inside modFiles[0],modFiles[1],modFiles[3] ? And how to count the data inside each modFiles ?

this.modFiles[0].length //i get error here

thanks so much

Answer

akrn picture akrn · Feb 2, 2018

Bidirectional binding is not supported for <input type="file">, since you're not allowed to set value on such inputs (value is only set after user chooses a file).

Use @change event instead:

<input type="file" multiple @change="handleFileChange($event, index)">

methods: {
  handleFileChange(evt, index) {
    // evt.target.files contains Array-like FileList object
  }
}

Update:

In order to show/hide your submit button based on count of selected files, introduce new data property:

data: {
  filesSelected: 0
},
methods: {
  handleFileChange(evt, index) {
    this.filesSelected = evt.target.files.length;
  }
}

And then use it in your template:

<input type="submit" v-show="filesSelected > 0" />