Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VueJS: trigger input file from button

Tags:

vue.js

I need to build a custom file uploader to upload a image profile but I don't want to use the original design of input file but hide it and show a button only to upload the picture.

And I know how to trigger the input file when a different button is clicked with jQuery and with AngularJS but I cannot find the way to do the same with VueJS, do you have any idea?

Kind regards!

like image 257
SoldierCorp Avatar asked Sep 19 '16 15:09

SoldierCorp


2 Answers

Vue style

This might be easier

<input type="file" ref="file" style="display: none" />
<button @click="$refs.file.click()">open file dialog</button>

If more is needed then $refs.file.$el should pointing to the DOM element. Here are the Properties and Methods that you can use.

like image 184
NiKO Avatar answered Nov 05 '22 04:11

NiKO


This is a quick, simple and dirty solution, but it works for me. Create a regular HTML file input, hide it with CSS, or with VueJS. Add a v-on:change event to the hidden file input.

<input id="fileInput" type="file" style="display:none" v-on:change="yourVueMethod()"/>

Create a button that will trigger the click event of the input field.

<button id="fileInputButton" onclick="document.getElementById('fileInput').click()">Open File</button>

And you can now do whatever you want in your method, just as normally. May not be the best solution, but easy to do.

like image 9
Zoltán Fraknói Avatar answered Nov 05 '22 03:11

Zoltán Fraknói