前端vue乐成办理滚动条滚动监听问题!

打印 上一主题 下一主题

主题 1672|帖子 1672|积分 5016

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

x
前端处置惩罚滚动条滚动变乱无非就是监听scroll变乱,但是我们经常会遇到 滚动变乱频繁触发无法正常获取滚动的元素,最常见的就是 处置惩罚滚动位置
vueuse------useScroll的使用

安装分析

vue3

  1. npm i @vueuse/core --save
复制代码
Vue2 的话还必要额外安装 @vue/composition-api

  1. npm i @vue/composition-api --save
复制代码
useScroll的使用

1.在@vueuse/core包下引入useScroll

  1. import { useScroll } from '@vueuse/core'
复制代码
  1. <!--需要滚动的容器-->
  2. <div id="container" ref="container" class="container"></div>
复制代码
  1. <!--第一个参数el(需要滚动的容器)-->
  2. this.$nextTick(() => {
  3.   const { x, y, isScrolling, arrivedState, directions } = useScroll(document.getElementById('container'))
  4.   this.x = x
  5.   this.y = y
  6.   this.isScrolling = isScrolling
  7.   this.arrivedState = arrivedState
  8.   this.directions = directions
  9. })
  10. <!--
  11. x:用于记录上次滚动的scrollLeft的值,
  12. y:记录上次滚动的scrollTop的值,
  13. isScrolling: 表示是否正在滚动,
  14. arrivedState: {top/right/bottom/left}表示滚动条是否到达指定边界,
  15. directions: {top/right/bottom/left} 表示滚动条正在滚动的方向
  16. -->
复制代码
  1. <!--第二个参数,可以设置偏移量offset(滚动条到达上下左右边界的一个偏移值,例如left设置为30, 则水平滚动条距离左边界30px时则认为到达了左边界)-->
  2. const { x, y, isScrolling, arrivedState, directions } = useScroll(document.getElementById('container'), { offset: { top: 0, bottom: 300, right: 30, left: 0 }})
复制代码
  1. <!--第二个参数,{behavior: smooth}设置平滑的滚动-->
  2. const { x, y, isScrolling, arrivedState, directions } = useScroll(document.getElementById('container'), { behavior: 'smooth' })
复制代码
2.可以手动设置滚动位置

3.这个方法也提供自定义指令的方式

自定义指令vScroll在@vueuse/components中
  1. import { vScroll } from '@vueuse/components'
  2. Vue.directive('scroll', vScroll)
  3. <div id="container" ref="container" v-scroll="onScroll" class="container"></div>
  4. onScroll({ x, y, isScrolling, arrivedState, directions }) {
  5.   this.x = x
  6.   this.y = y
  7.   this.isScrolling = isScrolling
  8.   this.arrivedState = arrivedState
  9.   this.directions = directions
  10. }
复制代码
4.场景

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

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

冬雨财经

论坛元老
这个人很懒什么都没写!
快速回复 返回顶部 返回列表