File input on change in vue.js

Using simple HTML / JS, one can view the JavaScript file objects of the selected files for an input element as follows:

<input type="file" id="input" multiple onchange="handleFiles(this.files)">

      

However, when converting it to "Vue", it doesn't work as expected and just returns undefined

instead of returning Array of File objects.

This is what it looks like in my Vue template:

<input type="file" id="file" class="custom-file-input" 
  v-on:change="previewFiles(this.files)" multiple>

      

If the function previewFiles

is just the following (found in methods):

  methods: {
    previewFiles: function(files) {
      console.log(files)
    }
  }

      

Is there an alternative / correct way to do this? Thanks to

+3


source to share


1 answer


Try it.

<input type="file" id="file" ref="myFiles" class="custom-file-input" 
  @change="previewFiles" multiple>

      



and in the parameters of your component:

data() {
  return {
    files: [],
  }
},
methods: {
  previewFiles() {
    this.files = this.$refs.myFiles.files
  }
}

      

+8


source







All Articles