Vue中Div的@scroll事件无法触发,如何实现滚动至底部检测
Hey there! Let's get to the bottom of why your @scroll event isn't triggering—this is a super common issue with scrollable containers in Vue, and it almost always boils down to missing styling on your target div.
The Root Cause
Your countriesContainerClass div isn't set up to be a scrollable container. For the scroll event to fire, the element needs two key CSS properties:
- A fixed (or max) height so content can overflow it
overflow-y: auto(orscroll) to enable vertical scrolling when content exceeds the height
Without these, the div will just expand to fit all its content, so there's never a scrollbar to trigger the event—hence why you don't see "scroll" in your console.
Step-by-Step Fix
Update Your Container Styling
Add these CSS rules to yourcountriesContainerClass(adjust the height to fit your layout):.countries-container { height: 400px; /* Set a fixed height based on your design needs */ overflow-y: auto; /* Show vertical scrollbar only when content overflows */ }If you're using scoped styles in Vue, make sure this class is properly applied to your div. You can even test this quickly with inline styles to confirm:
<div style="height: 400px; overflow-y: auto" v-if="showCountries" @scroll="onScroll">Verify the Scroll Target
Double-check that the scroll is happening on the div you bound the event to. If your inner<ul>is taking up all the space and scrolling instead, move the@scrollevent to the<ul>element instead.Test Your onScroll Method
Once the container is scrollable, scroll through your list—you should see "scroll" printed in the console. Your bottom detection logic will work as expected once the event fires:onScroll({ target: { scrollTop, clientHeight, scrollHeight } }) { console.log("scroll"); // This should now appear! if (scrollTop + clientHeight >= scrollHeight - 10) { // Add a small buffer for cross-browser accuracy console.log("bottom"); } }The
-10buffer helps account for minor rounding differences across browsers, making the bottom detection more reliable.
Quick Debug Tips
- Use your browser's DevTools to inspect the div: Check the Computed styles tab to confirm
heightandoverflow-yare set correctly. - Make sure no parent elements are interfering with the scroll behavior (e.g., a parent with
overflow: hiddenthat's hiding the scrollbar).
内容的提问来源于stack exchange,提问作者Jelena Ajdukovic

