wood4283's avatar

Browser/Window Scroll event from within a Component

How can I trigger a method within a component when the browser window is scrolled?

0 likes
2 replies
samfrjn11's avatar

Simply add an event listener as soon as the component is mounted. If you are using vue <2.0 replace mounted with ready.

export default{

    mounted(){
        window.addEventListener("scroll", runOnScroll);
    },

    methods: {
        myMethod(){
            console.log('scroll!');
        }
    }

}
1 like
wood4283's avatar
wood4283
OP
Best Answer
Level 20

@samfrjn11 Thanks. However, I had to add the event listener to my method and then return the function within the callback. When I tried to call my method the way you have it, it would only call it once when it mounted.

export default{
    mounted(){
        this.myMethod();
    },
    methods: {
        myMethod(){
            window.addEventListener("scroll", function(){
                console.log('scrolling');
            }
        }
    }
}
2 likes

Please or to participate in this conversation.