vue3 监听容器滚动到底部

佚名 / 2023-08-25 / 原文

在容器里面添加@scroll事件

<template>
  <div @scroll="scrolling" id="content">
    <p v-for="i in Array.from({length: 30}, (v, i) => i)">
      {{ i }}
    </p>
  </div>
  <div v-if="bottom">到达底部</div>
</template>

<script setup>
  import { ref } from 'vue'
   
  const bottom = ref(false)
   
  const scrolling = (e) => {
    const clientHeight = e.target.clientHeight
    const scrollHeight = e.target.scrollHeight
    const scrollTop = e.target.scrollTop
     
    if (scrollTop + clientHeight >= scrollHeight) {
      console.log('到底了!')
      bottom.value = true
    } else {
      bottom.value = false
    }
  }
</script>

<style>  
  #content {
    height: 200px; 
    overflow: auto; 
    border: 1px solid red; 
    padding: 0 10px;
  }
</style>