获取绑定事件的元素 [英] Get element where Event is binded

查看:47
本文介绍了获取绑定事件的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Vue 中的 @click 属性将事件绑定到一个元素(它的行为与 javascript .onclick 属性相同).

我遇到的问题是,当通过从子 DOM 节点单击事件传播来调用事件时,我将子 DOM 元素作为 target 属性,但我找不到一种干净的方法(无需搜索对于父级,因为该元素可能嵌套在内部深处)以访问事件在事件回调中注册到的 DOM 元素.

<td @click="onCellClick($event)"><div class="text"><span>默认</span>

</td>

解决方案

我认为混淆在于事件的 targetcurrentTarget

<块引用>

event.target 是触发事件调度程序触发的内容,而 event.currentTarget 是您分配给您的侦听器的内容.

Vue.component('cell', {模板:'#cell',方法: {onCellClick: 函数 (e) {控制台日志(e.currentTarget)}}});

I am binding an event to an element either using @click property in Vue (it behaves the same as javascript .onclick property).

The problem I have is when the event is called by propagating from the child DOM nodes click events I get the child DOM element as target property and I cannot find a way a clean way (without searching for the parents, as the element might me nested deep inside) to access the DOM element that the event was registered onto inside the event callback.

<td @click="onCellClick($event)">
  <div class="text">
    <span>default</span>
  </div>
</td>

解决方案

I think the confusion is with the event's target vs currentTarget

event.target is what triggers the event dispatcher to trigger and event.currentTarget is what you assigned your listener to.

Vue.component('cell', {
  template: '#cell',
  methods: {
    onCellClick: function (e) {
      console.log(e.currentTarget)
    }
  }
});

这篇关于获取绑定事件的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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