I'm trying to bind a input file to a button using Vue.js
Having the following:
<input type="file hidden>
<button>Choose</button>
In JQuery would be somthing like:
$('button').click(function() {
$('input[type=file]').click();
});
So, what this is doing is binding the click event on the button to the input file, this way I have complete control on the look of the button, it can even be a anchor or a image or any element to trigger the event to the input.
My question is: How can I accomplish this using Vue.js?
Thank you!
You can do this:
HTML:
<input id="fileUpload" type="file" hidden>
<button @click="chooseFiles()">Choose</button>
Vue.js:
methods: {
chooseFiles: function() {
document.getElementById("fileUpload").click()
},
...
EDIT - Update syntax:
methods: {
chooseFiles() {
document.getElementById("fileUpload").click()
},
...
Simplest way to do this is to stylize a label element like a button, HTML only.
Add a ref="file"
to your <input>
element and later use $refs.file
to access it.
<input ref="file" type="file">
<div @click="selectFile()">click to select a file</div>
methods:{
selectFile(){
let fileInputElement = this.$refs.file;
fileInputElement.click();
// Do something with chosen file
}
}
👌 Demo: https://codepen.io/Jossef/pen/QWEbNGv
you can use the label
html tag for doing this like below
<label for="upload-file" class="css-class">
<input type="file" id="upload-file" hidden @change="choosFile"/>
</label>
in this way you didn't need the button any more and you can customize the label with css
as the way you like it
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