Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

290
Vistas
How to use both props and mounted() with NuxtJS?

I'm new to NuxtJS and I'd want to use window.addEventListener on a particular component used on my page, but also remove the event when we change the page.

In React, I'd do something like this:

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

  return <div />
}

But, how do I do the same behaviour with NuxtJS 3?

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

// I want to use `window.addEventListener("keyup", props.close)`;
// I'd do something like this:
if (process.client) {
  window.addEventListener("keyup", props.close);
}
</script>

<template>
  <div />
</template>

The problem is how do I remove the event once the component will unmount? Is there a better way to do this?

about 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

A correct place for DOM-specific initialization is mounted hook, this won't require process.client check because it occurs only on client side. And it's mirrored with unmounted hook.

It's preferable to force a callback to be constant during the lifespan because changing a prop unintentionally will prevent event listener from being removed:

const { close } = props;

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

onUnmounted(() => {
  window.removeEventListener("keyup", close);
})
about 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda