Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

255
Views
How to remove event listener from Vue Component

I have a Vue2 component which contains an added eventListener i created on mounted. I was wondering how do i properly remove this listener when the component is destroyed?

<template>
    <div>
      ...
    </div>
  </template>
  
  <script>
  export default {
    mounted() {
        window.addEventListener('click', (evt) => {
          this.handleClickEvent(evt)
        })
    },
    destroyed() {
      //   window.removeEventListener('click', ????);
    },
    methods: {
      handleClickEvent(evt) {
        // do stuff with (evt) 
      },
    },
  }
  </script>
  
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You can use this.$el for whole component and destroy event like you created it:

Vue.component('Child', {
  template: `
    <div class="child">
      click for event
    </div>
  `,
  mounted() {
    this.$el.addEventListener('click', (evt) => {
      this.handleClickEvent(evt)
    })
  },
  beforeDestroy() {
    console.log('distroyed')
    this.$el.removeEventListener('click', (evt) => {
      this.handleClickEvent(evt)
    })
  },
  methods: {
    handleClickEvent(evt) {
      console.log(evt.currentTarget)
      // do stuff with (evt) 
    },
  },
})


new Vue({
  el: "#demo",
  data() {
    return {
      show: true
    }
  },
  methods: {
    toggleShow() {
      this.show = !this.show
    }
  }
})
.child {
  height: 150px;
  width: 200px;
  background: goldenrod;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="demo">
  <div>
    <button @click="toggleShow">mount/unmount component</button>
    <Child v-if="show" />
  </div>
</div>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!