From my own experience, implementing an event listener on scroll can result in a lot of excess activity being fed into the event stream, potentially causing performance issues especially when dealing with a hefty handleScroll
function.
I frequently utilize the method demonstrated in the top-rated answer, but I also incorporate debounce functionality on top of it, typically setting it to around 100ms
for optimal balance between performance and user experience.
Here's an example showcasing the highest rated solution with Lodash debounce integrated:
import debounce from 'lodash/debounce';
export default {
methods: {
handleScroll(event) {
// Implement any necessary code upon scrolling
this.isUserScrolling = (window.scrollY > 0);
console.log('calling handleScroll');
}
},
mounted() {
this.handleDebouncedScroll = debounce(this.handleScroll, 100);
window.addEventListener('scroll', this.handleDebouncedScroll);
},
beforeDestroy() {
// I changed from `destroyed` to `beforeDestroy` to provide a different perspective. Both lifecycle methods are effective.
window.removeEventListener('scroll', this.handleDebouncedScroll);
}
}
Experiment by altering the value of 100
to 0
and 1000
to observe the variations in how/when handleScroll
is triggered.
EXTRA: For a more concise and reusable approach, consider leveraging a library like vue-scroll
. This presents an excellent opportunity to delve into custom directives within Vue if you haven't explored them yet. Check out https://github.com/wangpin34/vue-scroll.
This helpful guide by Sarah Drasner in the Vue documentation delves into creating custom scroll directives: https://v2.vuejs.org/v2/cookbook/creating-custom-scroll-directives.html
For Vue 3 Enthusiasts
In Vue 3, opt for unmounted or beforeUnmount instead of beforeDestroy
.
Lifecycle hook beforeDestroy is not emitted in Vue3