Question:
I’m working on a Vue 3 component where I want to add a scroll event listener to change the header’s style when the user scrolls down the page. However, the event listener doesn’t seem to work, and no console logs appear when I scroll.
Here is a simplified version of my code:
<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue';
const isScrolled = ref(false);
const handleScroll = () => {
if (window.scrollY > 50) {
isScrolled.value = true;
} else {
isScrolled.value = false;
}
console.log('isScrolled', isScrolled.value);
};
onMounted(() => {
console.log('Mounted and adding scroll listener');
window.addEventListener('scroll', handleScroll);
});
onUnmounted(() => {
console.log('Removing scroll listener');
window.removeEventListener('scroll', handleScroll);
});
</script>
Problem:
The scroll event listener is added in onMounted, but it doesn’t trigger when I scroll the page. There’s no console output, and the isScrolled value doesn’t change.
What I’ve Tried:
Verified that the component mounts correctly (logs appear in the console during mounting).
Simplified the event listener to just log to the console, but still no success.