最近使用 uni-app 开发的一个 H5 项目,其中有一个 用 uni-app 原生 swiper 组件写的轮播。
今天领导在用的时候提出一个问题:你这个不支持鼠标滚轮啊?我就比较疑惑 uni-app 是移动端场景啊,谁用手机还外接个鼠标啊。
没办法,该改还得改,下面教程开始:
1、在 methods
内添加方法:
- methods: {
- handleScroll (e) {
- // 鼠标滚轮滚动 swiper
- if (this.curDot < 2) { // 如果index小于2: swiper-item 的数量 curDot: 当前显示的index
- this.swiper.curDot++
- } else {
- this.swiper.curDot--
- }
- }
- }
2、在 Mounted ()
方法里监听鼠滚轮(mousewheel
)。
- mounted () {
- // 监听鼠标滚轮
- window.addEventListener('mousewheel', this.handleScroll, false)
- }
现在,滚动鼠标滑轮试一下,发现 swiper 可以翻页了。
不过有个问题,不管鼠标滚轮上滑还是下滑, swiper 都是往下翻的。
还需要再改造一下:
鼠标滑轮滚动的时候会有一个 deltaY
属性,正直(100)为往下滑动,负值(-100)为向上滑动。
3、修改一下 methods
内的方法:
- methods: {
- handleScroll (e) {
- console.log('mouse scroll:', e.deltaY + 'px')
- // 鼠标滚轮滚动 swiper
- if (e.deltaY > 0 && this.curDot < 2) {
- this.swiper.curDot++
- } else if (e.deltaY < 0 && this.curDot > 0) {
- this.swiper.curDot--
- }
- }
- }
这里要注意,给 swiper 增加一个 change
事件:
- <swiper
- ...
- :current="curDot"
- @change="swiperChange"
- >
实时修改 swiper 的 index
:
- swiperChange (e) {
- this.curDot = e.detail.current
- }
这样就可以实现鼠标滚轮控制 swiper 翻页了,大家可以根据自己的需求做进一步的优化。
未经允许不得转载:前端资源网 - w3h5 » Vue&uni-app swiper 轮播支持鼠标滚轮翻页实现