Vue + better-scroll 实现移动端字母索引导航功能

2020-06-13 10:37:09易采站长站整理

this.scroll = new BScroll(this.$refs.listView, {
// 获取 scroll 事件,用来监听。
probeType: 3
})
}
}

使用 created 方法进行 better-scroll 初始化,使用 setTimeout 是因为需要等到 DOM 加载完毕。不然 better-scroll 获取不到 dom 就会初始化失败。

这里把方法写在两 methods 里面,这样就不会看起来很乱,直接调用就可以了。

初始化的时候传入两 probeType: 3,解释一下:当 probeType 为 3 的时候,不仅在屏幕滑动的过程中,而且在 momentum 滚动动画运行过程中实时派发 scroll 事件。如果没有设置该值,其默认值为 0,即不派发 scroll 事件。

给索引添加点击事件和移动事件实现跳转

首先需要给索引绑定一个 touchstart 事件(当在屏幕上按下手指时触发),直接使用 v-on 就可以了。然后还需要给索引添加一个 data-index 这样就可以获取到索引的值,使用 :data-index=”index” 。


<div class="list-shortcut">
<ul>
<li v-for="(item, index) in shortcutList"
class="item"
:data-index="index"
:key="item.id"
@touchstart="onShortcutStart"
@touchmove.stop.prevent="onShortcutMove"
>
{{ item }}
</li>
</ul>
</div>

绑定一个 onShortcutStart 方法。实现点击索引跳转的功能。再绑定一个 onShortcutMove 方法,实现滑动跳转。


created () {
// 添加一个 touch 用于记录移动的属性
this.touch = {}
// 初始化 better-scroll 必须要等 dom 加载完毕
setTimeout(() => {
this._initSrcoll()
}, 20)
},
methods: {
_initSrcoll () {
this.scroll = new BScroll(this.$refs.listView, {
probeType: 3,
click: true
})
},
onShortcutStart (e) {
// 获取到绑定的 index
let index = e.target.getAttribute('data-index')
// 使用 better-scroll 的 scrollToElement 方法实现跳转
this.scroll.scrollToElement(this.$refs.listGroup[index])

// 记录一下点击时候的 Y坐标 和 index
let firstTouch = e.touches[0].pageY
this.touch.y1 = firstTouch
this.touch.anchorIndex = index
},
onShortcutMove (e) {
// 再记录一下移动时候的 Y坐标,然后计算出移动了几个索引
let touchMove = e.touches[0].pageY
this.touch.y2 = touchMove

// 这里的 16.7 是索引元素的高度
let delta = Math.floor((this.touch.y2 - this.touch.y1) / 18)

// 计算最后的位置
// * 1 是因为 this.touch.anchorIndex 是字符串,用 * 1 偷懒的转化一下
let index = this.touch.anchorIndex * 1 + delta
this.scroll.scrollToElement(this.$refs.listGroup[index])
}
}