Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bind file input to a button using Vue.js

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!

like image 416
Roberto Murguia Avatar asked May 31 '16 01:05

Roberto Murguia


4 Answers

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()
    },
...
like image 182
crabbly Avatar answered Nov 09 '22 11:11

crabbly


Simplest way to do this is to stylize a label element like a button, HTML only.

like image 42
Andrew Powers Avatar answered Nov 09 '22 10:11

Andrew Powers


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

like image 7
Jossef Harush Kadouri Avatar answered Nov 09 '22 10:11

Jossef Harush Kadouri


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

like image 4
Farshad Fahimi Avatar answered Nov 09 '22 11:11

Farshad Fahimi