vue3中监听scroll事件的3种方法 |
您所在的位置:网站首页 › vue动态添加div标签添加事件 › vue3中监听scroll事件的3种方法 |
监听元素的滚动事件是很常见的一个需求了。下面介绍3种在vue3中监听元素滚动事件的方法。 1.添加事件监听:Event Listener 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) }){{ i }} 到达底部 #content { height: 200px; overflow: auto; border: 1px solid red; padding: 0 10px; } 2.@scroll event在容器里面添加@scroll事件。 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 } }{{ i }} 到达底部 #content { height: 200px; overflow: auto; border: 1px solid red; padding: 0 10px; } 3.使用useScroll插件首先安装@vueuse/core包 官网使用方法:useScroll npm install @vueuse/core组件里面使用方法如下: 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 }){{ i }} 到达底部 #content { height: 200px; overflow: auto; border: 1px solid red; padding: 0 10px; }
|
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |