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?
Vue v-model is a directive that creates a two-way data binding between a value in our template and a value in our data properties. A common use case for using v-model is when designing forms and inputs. We can use it to have our DOM input elements be able to modify the data in our Vue instance.
The file input type is used to identify resource(s) in the file structure, upload a file, or create a resource to upload. The file input element provides a GUI to select a file, and then represents a list of files that are selected with the option to change resource(s) until form submission.
To bind the value of an input element to a property of your component's data, use v-model="dataProperty" like so. Notice the input value starts out as Am I truly an alligator? , but when you change the input, the existentialQuestion property (and the h2 element) will update in real time.
Note: v-model only works with input which use value binding, where input type file doesn't use input value, it makes no sense to use input type file with v-model Thanks for contributing an answer to Stack Overflow!
To support v-model, the component accepts a value prop and emits an input event. Use the component like this: With that, the custom component supports v-model two-way binding. Let’s take it a step further. We might not want to use the default event and prop needed to add v-model support to our components.
The thing is, the way things are set up today, the model value will be file's path instead of file name (which I think is what @airtoxin expected). Take a look at this snippet. What do you guys think? Is this the expected behavior? Sorry, something went wrong. @rafaelrinaldi hi, thanks to your examples.
With that, the custom component supports v-model two-way binding. Let’s take it a step further. We might not want to use the default event and prop needed to add v-model support to our components. Thankfully, Vue allows us to customize it.
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/
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With