简体   繁体   English

Vue 2 - 监听滚动事件

[英]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:我试图在 vue 组件中监听滚动事件,但是当我尝试像这样设置它时:

<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?为什么不工作的第一种方法,这应该是做事的方式Vue公司?

What you were initially setting up:您最初的设置:

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

Will only detect scroll on that div.只会检测该 div 上的滚动。 That div would need to first be scrollable with overflow:scroll;该 div 需要首先使用overflow:scroll; or something similar, then when you scroll inside that div, the handleScroll will be triggered.或类似的东西,然后当您在该 div 内滚动时,将触发 handleScroll。

What you setup in javascript is listening to scroll on the window element.您在 javascript 中设置的是监听window元素上的滚动。 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.您所做的对于检测窗口上的滚动事件是正确的,但是请记住,只要该组件处于活动状态,这些事件才会被注册。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM