简体   繁体   English

在 Vue 中使用 window.addEventListener 多次触发事件

[英]Event fired multiple times with window.addEventListener in Vue

I have this html code inside my Vue component我的 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>

And that method clickOutside() is this:该方法 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");
        }
      });
    },

But when I click on that div the event is fired multiple times, this is the response in the console with a single click:但是,当我单击该 div 时,该事件被多次触发,这是控制台中的响应,只需单击一下:

在此处输入图像描述

Anyone maybe know how to fix it or why this is happening?任何人都可能知道如何解决它或为什么会发生这种情况?

This is fired by the element and its children, so you should add the self modifier to prevent that behavior :这是由元素及其子元素触发的,因此您应该添加self修饰符以防止该行为:

<div id="stats" class="" @click.self="clickOutside()">

For more details check this https://vuejs.org/guide/essentials/event-handling.html#event-modifiers有关更多详细信息,请查看此https://vuejs.org/guide/essentials/event-handling.html#event-modifiers

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:我最后做的是在 created 钩子上创建一个事件监听器,在 destroy 钩子上删除它,并添加一个检测目标的方法,这样:

created() {
    window.addEventListener("mouseup", this.onMouseUp);
  },
  destroyed() {
    window.removeEventListener("mouseup", this.onMouseUp);
  },
methods: {
    onMouseUp(e) {
      const clickedE1 = e.target;
      if (this.$el.contains(clickedE1)) {
        console.log("inside");
      } else {
        console.log("outside");
      }
    },
  },

And that was all, it finally worked the way I wanted.仅此而已,它终于按我想要的方式工作了。 Thank you for your responses.谢谢你的回复。

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

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