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

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

这样就可以实现索引的功能了。

当然这样是不会满足我们的对不对,我们要加入炫酷的特效呀。比如索引高亮什么的~~

移动内容索引高亮

emmm,这个时候就有点复杂啦。但是有耐心就可以看懂滴。

我们需要 better-scroll 的 on 方法,返回内容滚动时候的 Y轴偏移值。所以在初始化 better-scroll 的时候需要添加一下代码。对了,别忘了在 data 中添加一个 scrollY,和 currentIndex (用来记录高亮索引的位置)因为我们需要监听,所以在 data 中添加。


_initSrcoll () {
this.scroll = new BScroll(this.$refs.listView, {
probeType: 3,
click: true
})
// 监听Y轴偏移的值
this.scroll.on('scroll', (pos) => {
this.scrollY = pos.y
})
}

然后需要计算一下内容的高度,添加一个 calculateHeight() 方法,用来计算索引内容的高度。


_calculateHeight () {
this.listHeight = [] const list = this.$refs.listGroup
let height = 0
this.listHeight.push(height)
for (let i = 0; i < list.length; i++) {
let item = list[i] height += item.clientHeight
this.listHeight.push(height)
}
}
// [0, 760, 1380, 1720, 2340, 2680, 2880, 3220, 3420, 3620, 3960, 4090, 4920, 5190, 5320, 5590, 5790, 5990, 6470, 7090, 7500, 7910, 8110, 8870]// 得到这样的值

然后在 watch 中监听 scrollY,看代码:


watch: {
scrollY (newVal) {
// 向下滑动的时候 newVal 是一个负数,所以当 newVal > 0 时,currentIndex 直接为 0
if (newVal > 0) {
this.currentIndex = 0
return
}
// 计算 currentIndex 的值
for (let i = 0; i < this.listHeight.length - 1; i++) {
let height1 = this.listHeight[i] let height2 = this.listHeight[i + 1]

if (-newVal >= height1 && -newVal < height2) {
this.currentIndex = i
return
}
}
// 当超 -newVal > 最后一个高度的时候
// 因为 this.listHeight 有头尾,所以需要 - 2
this.currentIndex = this.listHeight.length - 2
}
}

得到 currentIndex 的之后,在 html 中使用。

给索引绑定

class -->  :class="{'current': currentIndex === index}"

最后再处理一下滑动索引的时候改变 currentIndex。

因为代码可以重复利用,且需要处理边界情况,所以就把

this.scroll.scrollToElement(this.$refs.listGroup[index])

重新写了个函数,来减少代码量。


// 在 scrollToElement 的时候,改变 scrollY,因为有 watch 所以就会计算出 currentIndex