简体   繁体   中英

Trigger an event on an element from another element in vue.js

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?

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>

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM