nuxt3 window.scroll only fires once

Viewed 47

I'm trying to listen to window.scroll in a Nuxt3 Content v2 app using the composition api.

<script setup>

function handleScroll(){
  console.log(window.pageYOffset)
}
if (process.client){
    window.addEventListener('scroll', this.handleScroll );
}
</script>

This fires exactly once but does not continously log the pageYOffset. How do I listen to the scroll event correctly? The target is a static website and I will not use SSR.

1 Answers

You should not use "this." when calling the handleScroll function since your approach is actually not using the composition api.

Right way in your case would be:

if (process.client){
    window.addEventListener('scroll', handleScroll);
}

Also I'd recommend changing the pageYOffset to scrollY since it's deprecated.

function handleScroll(){
    console.log(window.scrollY)
}
Related