You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue中Div的@scroll事件无法触发,如何实现滚动至底部检测

Fixing Vue's @scroll Event Not Firing for Div Scroll Detection

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 (or scroll) 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

  1. Update Your Container Styling
    Add these CSS rules to your countriesContainerClass (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">
    
  2. 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 @scroll event to the <ul> element instead.

  3. 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 -10 buffer 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 height and overflow-y are set correctly.
  • Make sure no parent elements are interfering with the scroll behavior (e.g., a parent with overflow: hidden that's hiding the scrollbar).

内容的提问来源于stack exchange,提问作者Jelena Ajdukovic

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 13:02:37