I have a div and a file input box. When we click on the div, the click of file input is to be triggered. How to do this in vue.js?
2 Answers
You will have to access the DOM to trigger the click event for the input.
But Vue can make it pretty convenient with the ref/$refs feature
With it, you can "mark" an element in the template and access it conveniently from within your component's code without relying on selectors.
new Vue({
el: '#app',
methods: {
clickHandler() {
this.$refs.fileInput.click()
}
}
})
.button {
padding: 10px;
border-radius: 5px;
border: 1px solid #CCC;
display: inline-block;
}
<script src="https://unpkg.com/[email protected]/dist/vue.js"></script>
<div id="app">
<div class="button" @click="clickHandler">Click me!</div>
<input type="file" ref="fileInput">
</div>
4 Comments
Vamsi Krishna
Oops you were 3 sec late
Roy J
Please always include some explanation of your code when you answer.
Linus Borg
Thanks for the reminder, edited my answer. Is that better?
Derzu
Why it does not works with a dropdown <select>, instead of a <input> ?