Passing dynamic scrollY value as a prop


#1

I want to detect a Y position of the mouse-scroll and pass it dynamically as a prop to a component Navbar. For this, I created an eventListener and stored the window.scrollY value to a variable scrollPos inside data(). After this I pass scrollPos as a prop to the Navbar component use v-bind:scrollPos=“scrollPos”. Unfortunately, the value that’s passed in the Navbar component is just 0, and does not change on any further mouse scrolling.

<Navbar v-bind:scrollPos="scrollPos" />

mounted() {

        console.log('Component mounted.');
        window.addEventListener('scroll', function(e) {
                this.scrollPos = window.scrollY;
                console.log(this.scrollPos);
        });

},
data() {
    return {
        scrollPos: 0
    }
}

I also tried to use v-on:scroll=“this.changeScrollPos()” method to check whether this method is accessed on any changes in mouse scroll, but it does not.

Can someone explain why this does not work and help me out in passing dynamic mouse scroll values to the Navbar component.


#2

That’s because inside

        window.addEventListener('scroll', function(e) {
                this.scrollPos = window.scrollY;
                console.log(this.scrollPos);
        });

this refers to window and not your Vue instance. Make it an arrow function and your code should work as intended.


#3

(post withdrawn by author, will be automatically deleted in 24 hours unless flagged)


#4

I converted it into an arrow function and it works. I am still not clear on why, would be helpful if someone explains it.

Thank you for helping me in solving the issue.