[Vuejs]-Trigger an event on an element from another element in vue.js

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/vue@2.3/dist/vue.js"></script>
<div id="app">
  <div class="button" @click="clickHandler">Click me!</div>
  <input type="file" ref="fileInput">
</div>

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();
    }
} 

Leave a comment