How to listen to the window scroll event in a VueJS component?

jeerbl picture jeerbl · Aug 22, 2017 · Viewed 96.2k times · Source

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!

Answer

jeerbl picture jeerbl · Aug 22, 2017

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.

export default {
  created () {
    window.addEventListener('scroll', this.handleScroll);
  },
  destroyed () {
    window.removeEventListener('scroll', this.handleScroll);
  },
  methods: {
    handleScroll (event) {
      // Any code to be executed when the window is scrolled
    }
  }
}

Hope this helps!