前端vue成功解决滚动条滚动监听问题!


前端处理滚动条滚动事件无非就是监听scroll事件,但是我们经常会遇到 滚动事件频繁触发无法正常获取滚动的元素,最常见的就是 处理滚动位置

vueuse------useScroll的使用

安装说明
vue3
npm i @vueuse/core --save
Vue2 的话还需要额外安装 @vue/composition-api
npm i @vue/composition-api --save
useScroll的使用
1.在@vueuse/core包下引入useScroll
import { useScroll } from '@vueuse/core'
<!--需要滚动的容器-->
<div id="container" ref="container" class="container"></div>
<!--第一个参数el(需要滚动的容器)-->
this.$nextTick(() => {
  const { x, y, isScrolling, arrivedState, directions } = useScroll(document.getElementById('container'))
  this.x = x
  this.y = y
  this.isScrolling = isScrolling
  this.arrivedState = arrivedState
  this.directions = directions
})
<!--
x:用于记录上次滚动的scrollLeft的值,
y:记录上次滚动的scrollTop的值,
isScrolling: 表示是否正在滚动,
arrivedState: {top/right/bottom/left}表示滚动条是否到达指定边界,
directions: {top/right/bottom/left} 表示滚动条正在滚动的方向
-->
<!--第二个参数,可以设置偏移量offset(滚动条到达上下左右边界的一个偏移值,例如left设置为30, 则水平滚动条距离左边界30px时则认为到达了左边界)-->
const { x, y, isScrolling, arrivedState, directions } = useScroll(document.getElementById('container'), { offset: { top: 0, bottom: 300, right: 30, left: 0 }})
<!--第二个参数,{behavior: smooth}设置平滑的滚动-->
const { x, y, isScrolling, arrivedState, directions } = useScroll(document.getElementById('container'), { behavior: 'smooth' })
2.可以手动设置滚动位置
3.这个方法也提供自定义指令的方式

自定义指令vScroll在@vueuse/components中

import { vScroll } from '@vueuse/components'

Vue.directive('scroll', vScroll)

<div id="container" ref="container" v-scroll="onScroll" class="container"></div>

onScroll({ x, y, isScrolling, arrivedState, directions }) {
  this.x = x
  this.y = y
  this.isScrolling = isScrolling
  this.arrivedState = arrivedState
  this.directions = directions
}
4.场景

1.滚动到底部,出现‘返回顶部’按钮
2.滚动到底部,加载新数据
3.其他

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

加仑小铁

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值