Categories
Vue Answers

How to Listen to the Window Scroll Event in a Vue.js Component with JavaScript?

Spread the love

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

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

Listen to the Window Scroll Event in a Vue.js Component

We can listen to the window scroll event in a Vue.js component by calling the window.addEventListener method to listen to the scroll event on the browser window.

For instance, we can write:

<template>
  <div id="app">
    <p v-for="n of 100" :key="n">{{ n }}</p>
  </div>
</template>

<script>
export default {
  name: "App",
  created() {
    window.addEventListener("scroll", this.handleScroll);
  },
  destroyed() {
    window.removeEventListener("scroll", this.handleScroll);
  },
  methods: {
    handleScroll(event) {
      console.log(window.scrollY);
    },
  },
};
</script>

We call window.addEventListener with 'scroll' in the created hook to add the handleScroll scroll event listener when the component is mounted.

And in the destroyed hook, we call window.renmoveListener to remove the handleScroll scroll event listener.

In the handleScroll method, we have the window.scrollY property to get the vertical scroll position.

In the template, we have some scrollable content. If we scroll through it, we should see the scrollY value logged.

Conclusion

We can listen to the window scroll event in a Vue.js component by calling the window.addEventListener method to listen to the scroll event on the browser window.

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 *