41

I can not use v-model with file input, Vue says I must use v-on:change. Ok so I can use v-on:change, but how can I bind the "content" of the input file to a data property?

Let's say I want to bind it in a component to this.file:

export default {
  data() {
    file: null
  },
  // ...
}

Here is the HTML part:

<input id="image" v-on:change="???" type="file">
<!--                           ^- don't know how to bind without v-model -->

How should I do the binding?

2 Answers 2

57

In the onchange event you should pass the event object to a function and handle:

onFileChange(e) {
  var files = e.target.files || e.dataTransfer.files;
  if (!files.length)
    return;
  this.createImage(files[0]);
},

For more information refer https://codepen.io/Atinux/pen/qOvawK/

2
  • 13
    this.createImage(files[0]); is a different method which is not included in the sinppet above, but the codepen link has it. I think it would be better if you could add that here as well, codepen link might expire, but the answer would remain.
    – Towkir
    Sep 22, 2019 at 16:51
  • Is it a good practice to use the "data:image/png;base64" plain text value for create the image on server-side? Dec 6, 2020 at 16:07
19

Using v-model with a file input makes no sense, because you can't set a value on a file input - so what should a two-way binding do here?

Just use v-on:change

2
  • 4
    Directly on the input tag, I agree, but in a component meant to handle file uploads in a generic way it is extremely normal to want to include a custom v-model pattern. (I get that the question is, literally, about type="file" but I think a better answer would be: make a custom input)
    – Damon
    Jan 14, 2019 at 19:05
  • the @change doesn't behave correctly when I upload the same file twice (it doesn't think anything has "changed") so setting a value to null would make sense in order to reset the input. Oct 29, 2021 at 16:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.