0

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?

1
  • 1
    You can do it with html element label Commented Jun 2, 2017 at 12:29

2 Answers 2

4

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>

Sign up to request clarification or add additional context in comments.

4 Comments

Oops you were 3 sec late
Please always include some explanation of your code when you answer.
Thanks for the reminder, edited my answer. Is that better?
Why it does not works with a dropdown <select>, instead of a <input> ?
0

Add a ref to you input and a click listener to your wrapper div

<div @click="triggerFileInput" id="wrapper">
    <input type="file" ref="myFile">
</div>


methods:{
    triggerFileInput(){
        this.$refs.myFile.click();
    }
} 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.