Skip to content
Advertisement

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>
  

Advertisement

Answer

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>
Advertisement