在移动端App中经常会涉及到下拉弹性回弹以及下拉加载更多等应用场景,原生滚动性能较差,滚动流畅度不高,Better Scroll是目前尚在维护的框架中较为流行的移动端滚动专用框架,支持惯性滚动、边界回弹、滚动条淡入淡出等效果的灵活配置,让滚动更加流畅,同时还提供了很多 API 方法和事件,以便我们更快地实现滚动场景下的需求,如下拉刷新、上拉加载。
针对目前在做的vuemall练手项目,记录一下vue-cli3内的接入和使用流程
最简单接入:仅用于提高滚动性能、位置侦测和下拉加载更多
- HTML中外部包裹容器class设置为wrapper,内部内容部分class设置为content
<div class="wrapper">
<ul class="content">
<button @click="btnClick">BTN</button>
<li>分类列表1</li>
<li>分类列表2</li>
<li>分类列表3</li>
...........
<li>分类列表98</li>
<li>分类列表99</li>
<li>分类列表100</li>
</ul>
</div>
- 注册滚动实例,并且设置probeType: 3(位置侦测),pullUpLoad: true(下拉加载更多)
<script>
import BScroll from 'better-scroll'
export default {
name: "Category",
data() {
return {
scroll: null
}
},
mounted() {
this.scroll = new BScroll(document.querySelector('.wrapper'), {
probeType: 3,
pullUpLoad: true
})
this.scroll.on('scroll', (position) => {
console.log(position)
})
this.scroll.on('pullingUp', () => {
console.log('加载更多')
})
},
methods: {
btnClick() {
console.log('btnClick')
}
},
}
</script>
其他功能:
惯性滚动
BetterScroll 在用户滑动操作结束时,还会继续惯性滚动一段。首先看一下源码中的 BScroll.prototype._end 函数,这是 touchend、mouseup、touchcancel、mousecancel 事件的处理函数,也就是用户滚动操作结束时的逻辑。
BScroll.prototype._end = function (e) {
...
if (this.options.momentum && duration < this.options.momentumLimitTime && (absDistY > this.options.momentumLimitDistance || absDistX > this.options.momentumLimitDistance)) {
let momentumX = this.hasHorizontalScroll ? momentum(this.x, this.startX, duration, this.maxScrollX, this.options.bounce ? this.wrapperWidth : 0, this.options)
: {destination: newX, duration: 0}
let momentumY = this.hasVerticalScroll ? momentum(this.y, this.startY, duration, this.maxScrollY, this.options.bounce ? this.wrapperHeight : 0, this.options)
: {destination: newY, duration: 0}
newX = momentumX.destination
newY = momentumY.destination
time = Math.max(momentumX.duration, momentumY.duration)
this.isInTransition = 1
}
...
}