Categories
Vue Answers

How to listen to the window scroll event in a Vue.js component?

Spread the love

Sometimes, we want to listen to the window scroll event in a Vue.js component.

In this article, we’ll look at how to listen to the window scroll event in a Vue.js component.

How to listen to the window scroll event in a Vue.js component?

To listen to the window scroll event in a Vue.js component, we can call window.addEventListener.

For instance, we write

export default {
  created() {
    window.addEventListener("scroll", this.handleScroll);
  },
  destroyed() {
    window.removeEventListener("scroll", this.handleScroll);
  },
  methods: {
    handleScroll(event) {
      // ...
    },
  },
};

to call window.addEventListener in the created hook to add the handleScroll method as the callback for the scroll event when the component is loading.

In the destroyed hook, we call window.removeEventListener to remove handleScroll as the scroll event listener when the component unmounts.

Conclusion

To listen to the window scroll event in a Vue.js component, we can call window.addEventListener.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *