I want to listen to the window scroll event in my Vue component. Here is what I tried so far:
<my-component v-on:scroll="scrollFunction">
...
</my-component>
With the scrollFunction(event)
being defined in my component methods but it doesn't seem to work.
Anyone has any idea how to do this?
Thanks!
Your requirements were on component but you ended with adding on body and not on component. Sure, you can do that on particular element as well but hey ...Here's what works directly with Vue custom components.
or
and define a method for handleScroll. Simple!
In my experience, using an event listener on scroll can create a lot of noise due to piping into that event stream, which can cause performance issues if you are executing a bulky
handleScroll
function.I often use the technique shown here in the highest rated answer, but I add debounce on top of it, usually about
100ms
yields good performance to UX ratio.Here is an example using the top-rated answer with Lodash debounce added:
Try changing the value of
100
to0
and1000
so you can see the difference in how/whenhandleScroll
is called.BONUS: You can also accomplish this in an even more concise and reuseable manner with a library like
vue-scroll
. It is a great use case for you to learn about custom directives in Vue if you haven't seen those yet. Check out https://github.com/wangpin34/vue-scroll.This is also a great tutorial by Sarah Drasner in the Vue docs: https://vuejs.org/v2/cookbook/creating-custom-scroll-directives.html
Actually I found a solution. I add an event listener on the
scroll
event when the component is created and remove the event listener when the component is destroyed.Hope this helps!
I think the best approach is just add ".passive"
I've been in the need for this feature many times, therefore I've extracted it into a mixin. It can be used like this:
This creates a reactive
position
property (can be named whatever we like) on the Vue instance. The property contains the window scroll position as an[x,y]
array.Feel free to play around with this CodeSandbox demo.
Here's the code of the mixin. It's thoroughly commentated, so it should not be too hard to get an idea how it works: