简体   繁体   中英

Event fired multiple times with window.addEventListener in Vue

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?

This is fired by the element and its children, so you should add the self modifier to prevent that behavior :

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

For more details check this 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() {
    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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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