事件用窗口多次发射。
我的VUE组件中有此HTML代码
<div id="stats" class="" @click="clickOutside()">
<ArticleStats
:article="article"
class="tw-mt-5 tw-hidden md:tw-flex"
/>
<div
@click="$router.push('/article/' + article.content_content_id)"
class="
tw-mt-5 tw-block tw-text-center tw-text-sm
md:tw-text-base
tw-cursor-pointer
tw-text-white
tw-p-2
tw-rounded-2xl
tw-w-full
tw-bg-red-400
hover:tw-bg-red-600 hover:tw-text-white
"
>
Leer más
</div>
</div>
,并且该方法Clickoutside()是这样:
clickOutside() {
console.log('hola')
window.addEventListener("mouseup", (e) => {
console.log(e);
const clickedE1 = e.target;
if (this.$el.contains(clickedE1)) {
console.log("inside");
} else {
console.log("outside");
}
});
},
但是,当我单击该事件多次触发该事件时,这是单击单击控制台中的响应:
有人可能知道如何修复它,或者为什么会发生这种情况?
I have this html code inside my Vue component
<div id="stats" class="" @click="clickOutside()">
<ArticleStats
:article="article"
class="tw-mt-5 tw-hidden md:tw-flex"
/>
<div
@click="$router.push('/article/' + article.content_content_id)"
class="
tw-mt-5 tw-block tw-text-center tw-text-sm
md:tw-text-base
tw-cursor-pointer
tw-text-white
tw-p-2
tw-rounded-2xl
tw-w-full
tw-bg-red-400
hover:tw-bg-red-600 hover:tw-text-white
"
>
Leer más
</div>
</div>
And that method clickOutside() is this:
clickOutside() {
console.log('hola')
window.addEventListener("mouseup", (e) => {
console.log(e);
const clickedE1 = e.target;
if (this.$el.contains(clickedE1)) {
console.log("inside");
} else {
console.log("outside");
}
});
},
But when I click on that div the event is fired multiple times, this is the response in the console with a single click:
Anyone maybe know how to fix it or why this is happening?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
![扫码二维码加入Web技术交流群](/public/img/jiaqun_03.jpg)
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我最终所做的是在创建的钩子上创建一个事件侦听器,将其删除在被破坏的钩子上,然后添加一种检测目标的方法,这样一来:
这就是全部,最终按照我想要的方式奏效。感谢您的回复。
What I finally did was create an event listener on the created hook, remove it on the destroyed hook, and add a method that detects the target, this way:
And that was all, it finally worked the way I wanted. Thank you for your responses.
这是由元素及其子女发射的,因此您应该添加
self
修饰符以防止这种行为:有关更多详细信息,请检查此 https://vuejs.org/guide/guide/esentials/estentials/event handling.html#event-modifiers
This is fired by the element and its children, so you should add the
self
modifier to prevent that behavior :For more details check this https://vuejs.org/guide/essentials/event-handling.html#event-modifiers