从 vue.js 中的另一个元素触发一个元素上的事件 [英] Trigger an event on an element from another element in vue.js

查看:34
本文介绍了从 vue.js 中的另一个元素触发一个元素上的事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 div 和一个文件输入框.当我们点击div时,就会触发文件输入的点击.如何在 vue.js 中做到这一点?

解决方案

您必须访问 DOM 才能触发输入的点击事件.

但是 Vue 可以通过 ref/$refs 功能

有了它,您可以标记"模板中的元素,并在组件代码中方便地访问它,而无需依赖选择器.

new Vue({el: '#app',方法: {clickHandler() {this.$refs.fileInput.click()}}})

.button {填充:10px;边框半径:5px;边框:1px 实心 #CCC;显示:内联块;}

<script src="https://unpkg.com/vue@2.3/dist/vue.js"></脚本><div id="应用程序"><div class="button" @click="clickHandler">点击我!</div><input type="file" ref="fileInput">

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>

这篇关于从 vue.js 中的另一个元素触发一个元素上的事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆