Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

291
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda