在我们日常的移动端项目开发中,处理滚动列表是再常见不过的需求了。 以滴滴为例,可以是这样竖向滚动的列表,如图所示:
我们在实现这类滚动功能的时候,会用到第三方库,better-scroll。
什么是 better-scroll
better-scroll 是一个移动端滚动的解决方案,它是基于 iscroll 的重写,它和 iscroll 的主要区别在这里。better-scroll 也很强大,不仅可以做普通的滚动列表,还可以做轮播图、picker 等等。
download:npm install better-scroll -S
封装Scroll组件
// Scroll组件
<template>
<div class="scroll-wrapper" ref="wrapper">
<div class="scroll-content">
<slot />
</div>
</div>
</template>
<script>
import BScroll from "better-scroll";
export default {
name: "Scroll",
props: {
probeType: {
type: Number,
default() {
return 0;
}
},
pullUpLoad: {
type: Boolean,
default() {
return false;
}
}
},
data() {
return {
scroll: null
};
},
mounted() {
this.scroll = new BScroll(this.$refs.wrapper, {
// 开启点击事件,默认是false
click: true,
// 0和1不监听滚动事件,2监听但是不监听手指松开后的滑动距离,3全部监听
probeType: this.probeType,
// 是否开启监听滚动到底部事件
pullUpLoad: this.pullUpLoad
});
//监听滚动的位置
if (this.probeType === 2 || this.probeType === 3) {
this.scroll.on("scroll", position => {
this.$emit("backTopScroll", position);
});
}
// 监听scroll滚动到底部
if (this.pullUpLoad) {
this.scroll.on("pullingUp", () => {
// console.log("滚动到底部了");
this.$emit("pullingUp");
});
}
},
methods: {
// 第一个参数x轴的距离,第二个参数y轴的距离,第三个参数是延迟时间
scrollTo(x, y, time = 500) {
this.scroll && this.scroll.scrollTo(x, y, time);
},
// 并且是为了保证this.scroll存在才执行
refresh() {
this.scroll && this.scroll.refresh();
},
finishPullUp() {
this.scroll && this.scroll.finishPullUp();
},
// 获取滚动的纵向距离
getScrollY() {
return this.scroll ? this.scroll.y : 0;
},
// 滚动到指定元素
scrollToElement(el, time) {
this.scroll.scrollToElement(el, time);
}
}
};
</script>
使用Scroll组件
<!-- BScroll滚动区域 -->
<scroll
:probe-type="3"
:pull-up-load="true"
@backTopScroll="backTopScroll"
@pullingUp="loadMore"
class="scroll-height"
ref="scroll"
>
<!-- 轮播图 -->
<my-swiper :swiper-list="banners" @swiperLoad="swiperLoad" />
<!-- 推荐分类 -->
<recommend-view :recommends="recommends" />
<!-- 本周流行 -->
<feature-view />
<!-- tabBarControl -->
<tab-control
:titles="tabControlTitles"
@tabClick="tabClick"
class="home-tab-control"
ref="tabControl2"
/>
<!-- 商品展示 -->
<goods-list :goods="goods[curType].list" />
</scroll>