What is the best way to utilize props and mounted() in NuxtJS together?

I'm a beginner with NuxtJS and I'm looking to implement window.addEventListener on a specific component within my page. However, I also need to ensure that the event is removed when the page changes.

In React, I would typically approach this as follows:

export default function MyComponent({ close }) {
  useEffect(() => {
    const handleKey = (e) => console.log(e.key);
    window.addEventListener("keyup", handleKey);
    return () => window.removeEventListener("keyup", handleKey);
  });

  return <div />
}

How can I achieve the same functionality in NuxtJS 3?

<script setup lang="ts">
interface ComponentProps { close: () => void; }
const props = defineProps<ComponentProps>();

// I want to use `window.addEventListener("keyup", props.close)`;
// Here's how I attempted it:
if (process.client) {
  window.addEventListener("keyup", props.close);
}
</script>

<template>
  <div />
</template>

The issue now is how do I remove the event once the component is unmounted? Is there a more efficient way to handle this situation?

Answer №1

The best spot to initialize DOM-specific tasks is within the mounted hook. Since this only happens on the client side, there's no need for a process.client check. Plus, it's important to pair it with an unmounted hook.

To ensure that a callback remains consistent throughout its lifespan, avoid accidentally changing props. This prevents any issues with event listeners not being properly removed:

const { close } = props;

onMounted(() => {
  window.addEventListener("keyup", close);
})

onUnmounted(() => {
  window.removeEventListener("keyup", close);
})

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

What is the best way to iterate over an indexed attribute in PHP?

Here is my ajax code snippet: $.ajax({ type: "POST", url: "bee_sesi_edit.php", data: 'serv_ruang='+ serv_ruangx +'&who='+names +'&sesi_d1='+ sesi_d1 +&apos ...

Aligning text to the right in Bootstrap 5 input fields

I'm trying to align the values of my inputs to the right. Any suggestions on how to achieve this? Here's a visual representation of what I'm looking for. This is the snippet from my code: <td style="text-align:center; vertical-alig ...

Limit the input to a maximum number of characters

I am in need of input boxes that only accept hexadecimal characters and I also want to set a maximum length for the input. Although I have successfully implemented accepting hex characters only, I am facing an issue when pasting a string - the invalid cha ...

Building and deploying Nuxt 3 applications in different environments

Currently, I am in the process of configuring development and production environments within Nuxt 3 for testing purposes. Specifically, I want to utilize a test endpoint if the app URL begins with develop-, staging-, or test-. For instance, when accessing ...

Is there a way for me to obtain the present value of the chosen button in the list below?

I am working with a group of three buttons labeled English, Hindi, and Urdu. How can I retrieve the value of the selected button in a JavaScript function? <div class="btn-group" data-toggle="buttons"> <label class="btn btn-primary active"> ...

Ways to receive alerts when a marker enters a polygon

Looking for a way to receive notifications if my marker enters any of the polygons on the map. Having trouble implementing it correctly, here is my current code: <!DOCTYPE html> <html> <head> <script src="http://ajax.googleapis.com ...

Secure communication and client-server API key protection

Looking for advice on building a JS app that communicates with my server using ajax. I need to give the client an api-key for authorization, but sending it through ajax poses security risks as it can easily be replicated by anyone. I don't want to req ...

React.js: The function useDef has not been defined

Attempting to create a React.js calculator application, my initial step was to delete the entire src folder and replace it with a new one containing the necessary elements for the web app. Here is the content of the index.js file: import React,{ useEffect, ...

Axios mistakenly includes an additional trailing slash in body parameters

Currently, in the process of developing an application utilizing React Native, I am faced with the challenge of communicating with an IoT chip that possesses minimal RAM memory. Due to this constraint, all logic must be executed on the client side. One sp ...

Is there a way to keep my fixed button at a consistent size while zooming on mobile devices?

There are no definitive answers to the questions regarding this issue. Some suggest stopping zoom altogether, while others recommend setting the width, which may not always solve the problem. I am working on a web application designed for mobile use with ...

The jQuery div enclosure technique

I am trying to wrap HTML around an existing div, here is what I have attempted: HTML: <input type="text" data-placeholder="username" /> It should look like this when rendered: <div class="placeholding-input"> <input type="text" data-pl ...

Invoke a function within an HTML element inserted using the html() method

Looking for help with a JavaScript function: function toggle_concessions(concessions) { var text = "<table>"+ "<tr><td class='concession-name'>gfhgfbfghfd</td><td class='op-encours&a ...

Transform a JSON array containing individual objects into a new JSON array with objects

My array contains objects with nested objects in each element, structured like this: [ { "person": { "name": "John", "isActive": true, "id": 1 } }, { "person": { "name": "Ted", "isActive": true, "id": 2 } } ] I ...

Clicking on an image in a jQuery autocomplete menu will trigger a data post to an Express

My jquery autocomplete menu is functioning properly, displaying a list of books with author, title, and book image. I am now looking to enhance it by allowing users to click on the book image and then have the book title posted to an express app.post metho ...

Instructions for adding a select dropdown feature in Angular 6 that includes a search filter. Additionally, tips on how to filter objects by their name property

I need to add an auto-complete feature in my Angular 6 app where the data is displayed as objects in a dropdown and filtered as we type. **template.html** <mat-form-field > <input matInput [matAutocomplete]="auto" [formControl]="customerFi ...

Is there a way to initiate the execution of a Spring Batch job from a Vue.js

I need to initiate a spring batch execution from an endpoint by calling a backend service. In my Vue application, I am attempting to make this call to trigger the batch process. async function executeBatch(data) { let response = await Axios.post(&apos ...

Troubles encountered when cascading val(), text(), and data()

Here is my JavaScript/jQuery code: $select.append($("<option />") .val(this.id) .text(this.text) .data('name', this.name) .data('isstorage', this.isstorage)); Although it successfully assigns values to t ...

Retrieve the values from hidden input fields that share the same name

How do I retrieve values from cName inputs? <form method="post" action=""> <input type="hidden" name="cName" value="test1" /> <input type="submit" name="get" /> </form> <form method="post" action=""> <input type="hi ...

Navigating through JSON data to retrieve specific values and executing repetitive actions

When the form is submitted, I am making an AJAX request to PHP code and this is the response I receive. var data = { "empty":{ "game_sais_no":"Season cannot contain empty value", "game_sc_no":"Category cannot contain empty value", ...

Receiving Request URL from XMLHttpRequest in PHP

I'm currently facing a dilemma as I work on a JavaScript script that is responsible for sending data from one of my forums to the server where a PHP script runs. The goal is to have the PHP script determine which JS output should be generated based on ...