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?