tx291
tx291

Reputation: 1331

simple scroll event not firing in Vue component

I am new to Vue and am trying to get the simplest scroll event handler set up. For some reason, it is not firing at all.

In my component, I have:

mounted () {
 window.addEventListener('scroll', this.runOnScroll);
},

methods: {
 runOnScroll () {
   console.log('scroll!');
 },
},

This is so basic, I don't understand why runOnScroll isn't firing!

Upvotes: 1

Views: 7729

Answers (2)

szoke
szoke

Reputation: 11

overflow auto was my issue.. after removing it, both wheel and sroll worked like a charm

https://forum.vuejs.org/t/problem-with-scroll-event-v-on-scroll-method-not-fire/48040/4

Upvotes: 1

zero298
zero298

Reputation: 26878

Make sure your window is tall enough to actually be able to scroll. If you just want to listen for when the user uses the mouse wheel, listen for the wheel event instead.

const app = new Vue({
  el: "#app",

  mounted() {
    window.addEventListener('scroll', this.runOnScroll);
    window.addEventListener('wheel', this.runOnWheel);
  },

  methods: {
    runOnScroll() {
      console.log('scroll!');
    },
    runOnWheel() {
      console.log('wheel');
    }
  },
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <div>hello world!</div>
  <div>hello world!</div>
  <div>hello world!</div>
  <div>hello world!</div>
  <div>hello world!</div>
  <div>hello world!</div>
  <div>hello world!</div>
  <div>hello world!</div>
  <div>hello world!</div>
  <div>hello world!</div>
  <div>hello world!</div>
  <div>hello world!</div>
  <div>hello world!</div>
  <div>hello world!</div>
  <div>hello world!</div>
  <div>hello world!</div>
  <div>hello world!</div>
  <div>hello world!</div>
  <div>hello world!</div>
  <div>hello world!</div>
  <div>hello world!</div>
  <div>hello world!</div>
  <div>hello world!</div>
</div>

Upvotes: 12

Related Questions