Vue&uni-app swiper 轮播支持鼠标滚轮翻页实现

最近使用 uni-app 开发的一个 H5 项目,其中有一个 用 uni-app 原生 swiper 组件写的轮播。

今天领导在用的时候提出一个问题:你这个不支持鼠标滚轮啊?我就比较疑惑 uni-app 是移动端场景啊,谁用手机还外接个鼠标啊。

没办法,该改还得改,下面教程开始:

1、在 methods 内添加方法:

  1. methods: {
  2.   handleScroll (e) {
  3.     // 鼠标滚轮滚动 swiper
  4.     if (this.curDot < 2) { // 如果index小于2: swiper-item 的数量 curDot: 当前显示的index
  5.       this.swiper.curDot++
  6.     } else {
  7.       this.swiper.curDot--
  8.     }
  9.   }
  10. }

2、在 Mounted () 方法里监听鼠滚轮(mousewheel)。

  1. mounted () {
  2.   // 监听鼠标滚轮
  3.   window.addEventListener('mousewheel', this.handleScroll, false)
  4. }

现在,滚动鼠标滑轮试一下,发现 swiper 可以翻页了。

不过有个问题,不管鼠标滚轮上滑还是下滑, swiper 都是往下翻的。

还需要再改造一下:

鼠标滑轮滚动的时候会有一个 deltaY 属性,正直(100)为往下滑动,负值(-100)为向上滑动。

3、修改一下 methods 内的方法:

  1. methods: {
  2.   handleScroll (e) {
  3.     console.log('mouse scroll:', e.deltaY + 'px')
  4.     // 鼠标滚轮滚动 swiper
  5.     if (e.deltaY > 0 && this.curDot < 2) {
  6.       this.swiper.curDot++
  7.     } else if (e.deltaY < 0 && this.curDot > 0) {
  8.       this.swiper.curDot--
  9.     }
  10.   }
  11. }

这里要注意,给 swiper 增加一个 change 事件:

  1. <swiper
  2.   ...
  3.   :current="curDot"
  4.   @change="swiperChange"
  5. >

实时修改 swiper 的 index :

  1. swiperChange (e) {
  2.   this.curDot = e.detail.current
  3. }

这样就可以实现鼠标滚轮控制 swiper 翻页了,大家可以根据自己的需求做进一步的优化。

未经允许不得转载:前端资源网 - w3h5 » Vue&uni-app swiper 轮播支持鼠标滚轮翻页实现

赞 (3)
分享到: +

评论 沙发

Avatar

换个身份

  • 昵称 (必填)
  • 邮箱 (选填)