I was trying to programmatically trigger .click() event of v-file-input because it has on the documentation at Vuetify.
but it shows an error this.$refs.imagePicker.click is not a function
am I missing something here?
Code Reproduction: https://codepen.io/kforr24/pen/ZEQweLP
I'm trying to upload an image using a certain button. Like that certain button would trigger a click event on the v-file-input.
document.getElementById ('your_input_type_file_element_id').click (); Example 1: We want to click the input file element automatically (programmatically). When the user clicks one button which is not the ‘file upload’ button of the input type file element, we can achieve it by using the following code.
In this article, we will learn how to programmatically fire click events on the input file element. Approach: Whenever you want to perform a click event programmatically, at your specific condition, just use JavaScript in-built click () function by DOM object. For example: document.getElementById ('your_input_type_file_element_id').click ();
Approach: Whenever you want to perform a click event programmatically, at your specific condition, just use JavaScript in-built click () function by DOM object. For example: document.getElementById ('your_input_type_file_element_id').click (); Example 1: We want to click the input file element automatically (programmatically).
The property value onclick=”initialize ()” is used to specify the function call when the user has clicked on the input. The variable theFile is created and the input element is selected using its id. The “document.body.onfocus = checkIt” line defines that the onfocus event is fired when an element gets focused.
@User28's solution (one of the comments below the question) works:
this.$refs.image.$refs.input.click()
For vue 3, refs are deprecated. I found that a workaround this is by using element id. You can use
<v-file-input
id="fileUpload"
accept=".pdf"
hide-input
prepend-icon=""
/>
<div>
<v-btn @click="getFile">
UPLOAD
</v-btn>
</div>
then on your event function for your button you can use,
const getFile = function () {
let fileUpload = document.getElementById('fileUpload')
if (fileUpload != null) {
fileUpload.click()
}
}
UPDATE February 2022
The best solution for any version is adding a id to the input or v-file-input then hide the input, in case you use v-file-input remove the icon by passing prepend-icon="" and hide-input .
<v-btn @click="document.getElementById('uploader').click()">
Upload Button text here
<v-file-input hide-input prepend-icon="" id="uploader"></v-file-input>
</v-btn>
in case you get this error:
TypeError: Cannot read properties of undefined (reading 'getElementById')
just put document in data
data: () => ({
document,
other: true
})
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