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:

JavaScript

But, how do I do the same behaviour with NuxtJS 3?

JavaScript

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