Search code examples
javascripthtmlvue.jsvue-componentwindow

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:

enter image description here

Anyone maybe know how to fix it or why this is happening?


Solution

  • 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.