Ways to detach event listener in Vue Component

One of my Vue2 components has a custom eventListener that I added in the mounted lifecycle hook. I am now trying to figure out the correct way to 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>
  

Answer №1

It is important to retain a reference to the click handler that has been registered, so that it can be removed later:

mounted() {
  this.clickHandler = () => { ... };
  window.addEventListener('click', this.clickHandler);
}

beforeDestroy() {
  window.removeEventListener('click', this.clickHandler);
}

However, if you already have a function named handleClickEvent defined in the component, there is no need to wrap it in an arrow function. You can directly use it as follows:

mounted() {
  window.addEventListener('click', this.handleClickEvent);
}

beforeDestroy() {
  window.removeEventListener('click', this.handleClickEvent);
}

In vue2, a handy feature allows for dynamic registration of a hook, enabling the addition and removal of the handler in mounted() without storing a reference within the component:

mounted() {
  const handler = () => { ... }; // local variable
  window.addEventListener('click', handler);
  this.$once('hook:beforeDestroy',
    () => window.removeEventListener('click', handler)
  );
}

https://v2.vuejs.org/v2/guide/components-edge-cases.html#Programmatic-Event-Listeners

Answer №2

If you want to access the entire component using this.$el and handle the destroy event similarly to how you set it up, follow this approach:

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>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it possible to convert the text.json file into a jQuery animation?

Looking to extract information from text.json and integrate it with my jquery.animation(). My goal is similar to the one demonstrated here. Instead of using "data" attributes like in that example, I want to parse the text based on the "ID" property as a k ...

Develop a COM API, or equivalent, tailored for a Node.js application

I have developed a JavaScript application that is designed to run on node.js. Is there a way to create a custom COM API or something similar for a Node.js application? For instance, in languages like C, C++, C#, etc., you can develop an application and t ...

Unable to reset iframe style height in IE8 using JavaScript

I am encountering an issue with resetting the height of an iframe using JavaScript. Here is the code snippet I am working with: var urlpxExt = document.getElementById('urlPx'); urlpxExt.style.height = "200px"; While this approach works well in m ...

Authenticating with passportjs using a Google Apps email address for verification

I am currently experimenting with using Passport.js along with a Google Apps email ID. I have successfully been able to authenticate using a gmail.com email ID, however, I am facing challenges when attempting to authenticate if the email ID is associated w ...

Transforming the unmanaged value state of Select into a controlled one by altering the component

I am currently working on creating an edit form to update data from a database based on its ID. Here is the code snippet I have been using: import React, {FormEvent, useEffect, useState} from "react"; import TextField from "@material ...

Particles are not appearing when using the Three.js shader material

Hey there, I've been working on a simple scene with a grid of particles in the shape of a cube. Check it out here: https://codepen.io/sungaila/pen/qqVXKM The issue I'm facing is that when using a ShaderMaterial, the particles don't seem to ...

Repeating Elements with Angular and Utilizing a Touch Keyboard

Currently, I am developing a table with various fields and the ability to add new rows. The goal is to display all the inputted data at the end. This application is specifically designed for touch screen monitors, so I have created a custom keyboard for in ...

How to download a dynamically generated PHP file to your local machine

I am trying to find a solution where the search results can be downloaded by the user and saved on their computer. Currently, the file is automatically stored on the server without giving the user an option to choose where to save it. In the search form, ...

Preventing touchstart default behavior in JavaScript on iOS without disrupting scrolling functionality

Currently experimenting with JavaScript and jQuery within a UIWebView on iOS. I've implemented some javascript event handlers to detect a touch-and-hold action in order to display a message when an image is tapped for a certain duration: $(document) ...

I am having trouble getting my JavaScript to load

I've hit a roadblock trying to understand why my JavaScript code isn't executing properly. Could someone kindly point out what I may have overlooked? :( JSFiddle Link HTML Snippet <div class="po-markup"> <br> <a href="# ...

Node receiving empty array as result after processing post request

My current task involves testing the post method on Postman. Strangely, every time I post the result it shows an empty array []. Upon further investigation by console logging on the node side, it also returns an empty array. CREATE TABLE users ( user_ ...

"Mastering the art of running a successful Dojo

As I delve into learning dojo, I encountered some peculiar syntax in a project on GitHub. dojo.declare('app.services.Favorites', [ dojo.store.Memory ], { constructor : function() { this.inherited(arguments); dojo.subscribe(& ...

Tips for fixing the issue of "module ./response not found" in Node.js Express

Whenever I execute the command $ npm start this error message appears > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="8feefcfce6e8e1e2eae1fbbccfbea1bfa1bf">[email protected]</a> start > nodemon server.js ...

Should a React application perform a complete refresh when a file is reloaded?

Recently, I delved into the world of React and learned about one of its key benefits: updating only the necessary DOM elements. However, as I began building an app from scratch, I encountered a situation where every time I saved the .js file, it resulted ...

Is there a way to determine the size of an array following the use of innerHTML.split?

There is a string "Testing - My - Example" I need to separate it at the " - " delimiter. This code will help me achieve that: array = innerHTML.split(" - "); What is the best way to determine the size of the resulting array? ...

Switching between light and dark themes in a Next.js application with Ant Design v5 theme toggle

In my Next.js application using Ant Design v5, I am working on implementing a dynamic theme toggle to switch between light and dark modes. The issue I'm facing is that the initial theme settings work correctly, but subsequent changes to the isDarkMode ...

Reasons for the failure of file uploads from the React frontend to the backend system

Recently, I embarked on a new project that involves using React for the front-end and Node for the back-end. The main requirement of this project is to upload multiple images from the front-end, with the back-end handling the file uploads to Cloudinary. I ...

Tips for cutting down on bundle size in your WEBPACK setup when using VUEJS

I have tried numerous tutorials to reduce the size of my bundle, but none of them seem to be affecting the bundle size and I can't figure out why. Every time I integrate new code into webpack, the bundle size remains unchanged. (The application is c ...

Looping through an array of nested objects using Vue

I have encountered a challenge with accessing specific data within an array that I am iterating over. The array is structured as follows, using Vue.js: companies: [ name: "company1" id: 1 type: "finance" additionalData: "{& ...

What is the best way to retrieve a JSON key in ReactJS?

I am currently facing a rendering issue. In my componentDidMount function, I am using axios to make a GET call and then updating the state with the received JSON data. The problem arises when I try to access the keys of the JSON in the render method becau ...