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:
JavaScript
x
10
10
1
export default function MyComponent({ close }) {
2
useEffect(() => {
3
const handleKey = (e) => console.log(e.key);
4
window.addEventListener("keyup", handleKey);
5
return () => window.removeEventListener("keyup", handleKey);
6
});
7
8
return <div />
9
}
10
But, how do I do the same behaviour with NuxtJS 3?
JavaScript
1
15
15
1
<script setup lang="ts">
2
interface ComponentProps { close: () => void; }
3
const props = defineProps<ComponentProps>();
4
5
// I want to use `window.addEventListener("keyup", props.close)`;
6
// I'd do something like this:
7
if (process.client) {
8
window.addEventListener("keyup", props.close);
9
}
10
</script>
11
12
<template>
13
<div />
14
</template>
15
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:
JavaScript
1
10
10
1
const { close } = props;
2
3
onMounted(() => {
4
window.addEventListener("keyup", close);
5
})
6
7
onUnmounted(() => {
8
window.removeEventListener("keyup", close);
9
})
10