50

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

63

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/

Sign up to request clarification or add additional context in comments.

2 Comments

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.
Is it a good practice to use the "data:image/png;base64" plain text value for create the image on server-side?
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

3 Comments

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)
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.
What to when i have to set the same in edit form. when the image is already there is the v-model but the input still throws a required validation as we are not able to set the v-model there.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.