简体   繁体   English

从 vue.js 中的另一个元素触发一个元素上的事件

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

I have a div and a file input box.我有一个 div 和一个文件输入框。 When we click on the div, the click of file input is to be triggered.当我们点击 div 时,会触发文件输入的点击。 How to do this in vue.js?如何在 vue.js 中做到这一点?

You will have to access the DOM to trigger the click event for the input.您必须访问 DOM 才能触发输入的点击事件。

But Vue can make it pretty convenient with the ref / $refs feature但是 Vue 可以通过ref / $refs功能使它变得非常方便

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为您的输入添加一个ref并为您的包装器div添加一个单击侦听器

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


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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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