vue3中监听scroll事件的3种方法

监听元素的滚动事件是很常见的一个需求了。下面介绍3种在vue3中监听元素滚动事件的方法。

1.添加事件监听:Event Listener

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
 
const content = ref()
const bottom = ref(false)
 
const doScroll = (event) => {
  const scrollHeight = event.target.scrollHeight
  const scrollTop = event.target.scrollTop
  const clientHeight = event.target.clientHeight
 
  if (scrollTop + clientHeight >= scrollHeight) {
    console.log('到底了!')
    bottom.value = true
  } else {
    bottom.value = false
  }
}
 
onMounted(() => {
  content.value.addEventListener('scroll', doScroll)
})
   
onUnmounted(() => {
  content.value.removeEventListener('scroll', doScroll)
}) 
</script>
 
<template>
  <div ref="content">
    <p v-for="i in Array.from({length: 30}, (v, i) => i)">
      {{ i }}
    </p>
  </div>
  <div v-if="bottom">到达底部</div>
</template>
 
<style>  
  #content {
    height: 200px; 
    overflow: auto; 
    border: 1px solid red; 
    padding: 0 10px;
  }
</style>

2.@scroll event

在容器里面添加@scroll事件。

<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>
 
<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>
 
<style>  
  #content {
    height: 200px; 
    overflow: auto; 
    border: 1px solid red; 
    padding: 0 10px;
  }
</style>

3.使用useScroll插件

首先安装@vueuse/core包

官网使用方法:useScroll

npm install @vueuse/core

组件里面使用方法如下:

<script setup>
import { ref, computed } from 'vue'
import { useScroll } from '@vueuse/core'
 
const content = ref()
 
const { arrivedState } = useScroll(content)
 
const bottom = computed(() => {
  if (arrivedState.bottom) {
    console.log('到底了!')
    return true
  }
 
  return false
})
</script>
 
<template>
  <div id="content" ref="content">
    <p v-for="i in Array.from({ length: 30 }, (v, i) => i)">{{ i }}</p>
  </div>
  <div v-if="bottom">到达底部</div>
</template>
 
<style>
#content {
  height: 200px;
  overflow: auto;
  border: 1px solid red;
  padding: 0 10px;
}
</style>

 

posted @ 2023-04-03 18:01  前端[色色]  阅读(20066)  评论(0编辑  收藏  举报