Preface
In uni-app, listening to page scrolling usually uses onPageScroll lifecycle function or @scroll event listener. Which one is used depends on your scenario and needs. The following will introduce these two methods separately.
1. Use the onPageScroll lifecycle function
onPageScroll is a lifecycle function unique to uni-app pages, which is triggered when the page is scrolling. This function receives an object as a parameter, which contains scroll-related information, such as scrollTop (vertical scroll distance), scrollLeft (horizontal scroll distance), etc.
export default { onPageScroll: function(e) { ('Scrolling distance:', ); // Vertical scroll distance// Here you can perform corresponding operations based on the values in the e object}, // Other page life cycle functions or data, methods, etc.}
Note: onPageScroll is mainly used to listen for scrolling events of the entire page, rather than scrolling of a single component or element.
2. Use @scroll event listener
If your requirement is to listen for scroll events of a specific component (such as scroll-view), you should use the @scroll event listener. scroll-view is a component of a scrollable view area provided by uni-app, similar to the HTML div element but adds scrolling functionality.
First, you need to use the scroll-view component in the page's .vue file and bind a handler through the @scroll property to listen for scroll events.
<template> <view> <scroll-view class="scroll-view" scroll-y="true" @scroll="handleScroll"> <!-- Here is your scrolling content --> <view v-for="(item, index) in 100" :key="index" class="scroll-item">{{ item }}</view> </scroll-view> </view> </template> <script> export default { methods: { handleScroll: function(e) { ('Scrolling event triggers', ); // Get the distance from the top of the scroll bar// Here you can execute the logic you want} } } </script> <style> .scroll-view { height: 300px; /* Limited height to generate scrolling */ width: 100%; } .scroll-item { height: 50px; /* Example height */ line-height: 50px; text-align: center; border-bottom: 1px solid #ccc; } </style>
In this example, the scroll-y="true" property of the scroll-view component indicates that vertical scrolling is allowed, and @scroll="handleScroll" binds the handle function handleScroll for the scroll event. In the handleScroll function, you can get the distance from the top of the scroll bar and execute the corresponding logic accordingly.
Summarize:
If you need to listen to the scrolling of the entire page, use onPageScroll; if you need to listen to the scrolling of a component (such as scroll-view), use the @scroll event listener.
This is the end of this article about two commonly used methods of scrolling on uniapp monitoring pages. For more relevant uniapp monitoring pages, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!