Skip to content
Advertisement

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?

Advertisement

Answer

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);
})
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement