Watch window.scrollY changes in Vuejs

2020 Updated:

Use @scroll.passive to watch scroll of any element in component:

Example:

Template

<div class="room_message-stream" @scroll.passive="handleScroll">
      <ul class="room_message-stream__list">
        <li class="room_message-stream__list-item">...</li>
      </ul>
</div>

Methods:

handleScroll (e) {
  var scrollPos = e.target.scrollTop
}

window properties can't be used reactively like that. Instead, you'd have to listen to the window's scroll event and respond accordingly:

mounted() {
  window.addEventListener("scroll", this.onScroll)
},
beforeDestroy() {
  window.removeEventListener("scroll", this.onScroll)
},
methods: {
  onScroll(e) {
    this.windowTop = window.top.scrollY /* or: e.target.documentElement.scrollTop */
  }
}

Edit Watching scrollTop in Vue


For me none of the above worked.

I had to pass true as 3rd parameter in add/remove scroll listener:

mounted() {
  window.addEventListener("scroll", this.onScroll, true)
},
beforeDestroy() {
  window.removeEventListener("scroll", this.onScroll, true)
},
methods: {
  onScroll(e) {
    this.windowTop = e.target.scrollTop;
  }
}

3rd parameter: You should be able to attach a document-level listener with a third parameter of true to capture the scroll events on all elements. Here's what that looks like:

document.addEventListener('scroll', function(e){ }, true);

The true at the end is the important part, it tells the browser to capture the event on dispatch, even if that event does not normally bubble, like change, focus, and scroll.