Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

285
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!