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>
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
2018-04-03 Framework 7 之 Smart select 选择后自动隐藏