简体   繁体   中英

Vue.js: how to react to page scrolling?

I've the need to react to window (viewport) scrolling to be able to detect when an element is visible or not.

The final goal is create something SIMILAR but not equal to an infinite scroller.

I want to learn to make it by myself. Do not link me plugins Please, I need to understand Vue.js before constructing over other's plugins.

How can I detect page (windows, or better the viewport) scrolling and resizing using Vue.js?

OR

How can I overseer the vertical position of an element, a div or a span, to react when it's near to be visibile ?

In the doc I found the @scroll , but it react to the scrolling of an element, not of the page.

There is a good suggestion here: https://github.com/vuejs/Discussion/issues/324#issuecomment-240978025

I duplicate the code here for posterity.

data () {
  return {
    scrolled: false
  };
},
methods: {
  handleScroll () {
    this.scrolled = window.scrollY > 0;
  }
},
created () {
  window.addEventListener('scroll', this.handleScroll);
},
destroyed () {
  window.removeEventListener('scroll', this.handleScroll);
}

You need to add a listener to the global scroll event on the window object.

window.addEventListener('scroll', listener)

You can find good advice on how to handle this event properly on MDN: https://developer.mozilla.org/en-US/docs/Web/Events/scroll

You can use Node#getBoundingClientRect to compute whether your node is visible, this method will provide you with the top position of your node within its scrollable container, you can use the offsetTop property alternatively. To do so you have to retrieve the viewport height, which is window.innerHeight is your case, and your current scroll position, which is window.scrollY in your case.

Then you can do something like that:

isVisible = innerHeight - scrollY > offsetTop - scrollY

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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