vue.js 单击事件目标给出元素或其子元素,而不是父元素

axkjgtzd  于 7个月前  发布在  Vue.js
关注(0)|答案(2)|浏览(82)

我有这个HTML元素:

<div class="list-group">
    <a href="javascript:;" @click="showDetails(notification, $event)" class="list-group-item" v-for="notification in notifications" :key="notification.id">
        <h4 class="list-group-item-heading" v-text="notification.title" />
        <p class="list-group-item-text" v-text="notification.created_at|moment" />
    </a>
</div>

字符串
这个JavaScript:

return new Vue({
    methods: {
        showDetails: function (notification, event) {
          this.notification = notification

          console.info(event.target)
        }
    }
}


问题是event.target返回的是我点击的元素,这意味着它可以是a元素,也可以是它的子元素(h4p)。
如何获取a元素(具有@click处理程序的元素),即使用户单击了它的一个子元素?

6tr1vspr

6tr1vspr1#

使用event.currentTarget,它指向你附加了监听器的元素。它不会随着事件冒泡而改变
https://developer.mozilla.org/en-US/docs/Web/API/Event/currentTarget

woobm2wo

woobm2wo2#

CSS的替代解决方案:

a * {
    pointer-events: none;
}

字符串
元素永远不是指针事件的目标;但是,如果子元素将指针事件设置为其他值,则指针事件可能会将其子元素作为目标。在这些情况下,指针事件将在事件捕获/冒泡阶段期间在去往/来自子元素的过程中适当地触发此父元素上的事件侦听器。
参考:https://developer.mozilla.org/en-US/docs/Web/CSS/pointer-events#Values

相关问题