Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue 2 - on listening on scroll event

I am trying to listen to scroll event in vue component, but when I have tried to set it up like this:

<div id="app"
     :class="{'show-backdrop': isLoading || showBackdrop}"
@scroll="handleScroll">

And then in the methods:

  handleScroll () {
    const header = document.querySelector('#header');
    const content = document.querySelector('#content');
    const rect = header.getBoundingClientRect();
    const scrollTop = window.pageYOffset || document.documentElement.scrollTop;
    const headerTop = rect.top + scrollTop;

    if (rect.top <= 0) {
      header.classList.add('fixed');
      content.classList.add('content-margin');
    } else {
      header.classList.remove('fixed');
      content.classList.remove('content-margin');
    }
  }

That is not working. I had to do a workaround like this:

beforeMount () {
  window.addEventListener('scroll', this.handleScroll);
},
beforeDestroy () {
  window.removeEventListener('scroll', this.handleScroll);
}

Why is the first approach not working, that should be the Vue way of doing things?

like image 219
Leff Avatar asked Nov 03 '17 08:11

Leff


1 Answers

What you were initially setting up:

<div id="app"
     :class="{'show-backdrop': isLoading || showBackdrop}"
@scroll="handleScroll">

Will only detect scroll on that div. That div would need to first be scrollable with overflow:scroll; or something similar, then when you scroll inside that div, the handleScroll will be triggered.

What you setup in javascript is listening to scroll on the window element. This will get triggered any time you scroll the page. What you did is correct for detecting scroll events on the window, however, keep in mind that these events will only be registered as long as this component is alive.

like image 127
Amrit Kahlon Avatar answered Nov 13 '22 19:11

Amrit Kahlon