Managing keypress events on a single page within Vue Router

Looking for a solution in my Vue.js SPA, where I have a specific page requiring keyboard interaction and using Vue Router for navigation.

Currently, I have set up the following to handle keyboard events:

const interactiveComponent = {
    //
    methods: {
        handleKeyboard(event) {
            // do something
        }
    },
    created() {
        document.addEventListener('keydown', this.handleKeyboard);
    },
    //
};

The issue arises when leaving the page as the handler remains active.

An even bigger problem occurs when revisiting the page, causing the handler to register multiple times and triggering the event more than once.

Is there a recommended convention in Vue.js to address this type of persistent handler?

Answer №1

In order to properly clean up after your Vue component, make sure to remove the event listener in either the beforeDestroy or destroyed hook.

const interactiveComponent = {
    //
    methods: {
        handleKeyboard(event) {
            // do something
        }
    },
    created() {
        document.addEventListener('keydown', this.handleKeyboard);
    },
    beforeDestroy() {
        document.removeEventListener('keydown', this.handleKeyboard);
    },
};

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

Transferring a document using axios to the Laravel framework

I am currently utilizing the Quasar file picker to capture files from users and send them to a Laravel controller using Axios. However, when I send the data to the Laravel controller, I am receiving an empty object. Can someone assist me in resolving this ...

AngularJS Datepicker - calendar dropdown does not update when the model changes

I've been facing a challenge with the AngularJs datepicker in my project for some time now. Within my application, users have the option to either manually select a date using the calendar or click on "This Month" to automatically set the date to the ...

Creating a fade in or fade out effect in AJAX without using jQuery is a simple yet

Is there a simple way to achieve fade in or fade out effects in ajax without relying on jQuery? I'm looking for a solution that can add color or background color to make it visually appealing, especially for small web pages with poor internet connecti ...

The value of type 'X' cannot be assigned to type 'Y' or 'undefined'

In my code, there is a component that requires a prop with an enum value: export enum AType { some = "SOME", word = "WORD", } const MyComponent = (arg: AType) => {} When I try calling this component like so: <MyComponent ar ...

Creating a dynamic map in AngularJS by parsing and utilizing data from a JSON file

Looking to create a map from JSON data returned by a RESTFUL WEB Service using AngularJS. Here is an example of the JSON format: myJSON = [{ id: 8, color: "red", value: "#f00" }, { id: 37, color: "green", value: "#0f0" }, { id ...

Utilizing the sAjaxSource property in Datatables to fetch data through Ajax from multiple tables while dynamically passing arguments

I am facing an issue with populating two datatables using data retrieved from a flask API through a GET request. My data source URL is localhost:5000/data, but for some reason, I am unable to display the data in the datatables. Interestingly, when I use a ...

Is it necessary to use both Vue Router and Express when incorporating Firebase into your project?

I am embarking on creating a simple application that will encompass various views, user authentication, data collection, database storage, and backend functionality to process and display the stored information. My chosen technology stack consists of Vue. ...

When incorporating pinia with Vue, encountering an error with the decorator that says "Error: Unable to access 'useCoreStore' before initialization" may happen

While implementing the vue-facing decorator in my current project, I encountered an issue with setting up pinia. The structure of my component resembles the example provided here: I have verified that decorators like @Setup are functioning correctly, ind ...

Reorganize external dependencies in the wwwroot directory using gulp

In my development setup using VS 2015, ASP.net vnext, Angular 2, Typescript, and gulp.js, I have successfully automated the process of moving my scripts/**/*.ts files to the wwwroot/app folder. Now, I am looking to extend this automation to include my libr ...

tips for transforming a javascript string into a function invocation

I am faced with the challenge of turning the string logo.cr.Button into a function call. Here is the code I'm working with: logo.cr.Button = function(){ //something } var strg = 'logo.cr.Button'; strg(); When I attempt to execute strg(); ...

Loop through the component name and route path in ReactJs to efficiently organize and structure your application

In my route file coding for ASP.NET, I am creating routes by fetching details from the backend. Successfully getting details like [Contacts, Pipelines, Stages]. import * as React from 'react'; import { BrowserRouter, Redirect, Route } from &apos ...

Is it possible to smoothly transition from one background image to another in CSS or JavaScript?

Most tutorials I've come across suggest using a background image with a linear gradient overlay, but that solution doesn't suit my needs: I have two adjacent divs with background images, slightly overlapping by 50px. I wish to create a gradient ...

Is there a way to transform time into a percentage with the help of the moment

I am looking to convert a specific time range into a percentage, but I'm unsure if moment.js is capable of handling this task. For example: let start = 08:00:00 // until let end = 09:00:00 In theory, this equates to 100%, however, my frontend data ...

Refresh database records

I am currently using grails and I am exploring ways to update my database table utility by selecting values from two drop down menus. These drop down menus are populated with values from the database based on user selections from another drop down menu. My ...

Refreshing the child component based on the child's action and sending information to the parent in a React application

Within my Parent Component, I am utilizing an Ajax call to populate two children Components. C1 requires the data only once, while C2 has the ability to fetch additional data through subsequent Ajax calls and needs to render accordingly. I find it more co ...

Yeoman - Storing global settings efficiently

I have recently developed a Yeoman generator and am now looking to incorporate prompts for certain global configurations. My goal is to have the generator prompt users for their GitHub username and token during the initial run, and then somehow store this ...

substitute elements within an array using elements from a different array

Looking to swap object(s) in an array with another array while maintaining the original order. Here is arrayOne: [ { "color": "#f8edd1", "selected": true }, { "color": "#d88a ...

Navigating through a large array list that contains both arrays and objects in Typescript:

I have an array containing arrays of objects, each with at least 10 properties. My goal is to extract and store only the ids of these objects in the same order. Here is the code I have written for this task: Here is the structure of my data: organisationC ...

In JavaScript, where are the values saved?

Can you clarify how JavaScript handles storage for primitive types and objects? Are primitive types always stored on the stack and objects on the heap, even within the scope of a function's execution? Also, are globally scoped variables and functions ...

Is it possible to trigger an event in Laravel prior to the expiration of a user's login session?

To keep track of when a user logs out, I have set up an event that is triggered after clicking the logout button. The code below demonstrates how I store the logout time: <?php namespace App\Listeners; use App\UserTrack; use Carbon\Carb ...