记录一下使用"better-scroll"时遇到的坑
记录一下使用"better-scroll"时遇到的坑使用场景:项目需要使用到了better-scroll 要求页面滑动顺畅,支持上拉刷新、下拉加载 已经返回到指定位置
前人的坑:一开始并没有使用better-scroll 而是用的vant 的组件,同样支持上拉刷新、下拉加载 但是在点击返回到指定位置 和点击详情返回时出现了问题,无法记录滑动位置以及定位不到指定元素位置
better-scroll写法
先将其写成组件
<template>
<div class="wrapper" ref="wrapper">
<div>
<div class="loaddingText" v-if="isLoadingTop">{{ topPullText }}</div>
<slot></slot>
<div class="loaddingTextBottom" v-if="isLoading">{{ bottomPullText }}</div>
</div>
</div>
</template>
<script>
import BScroll from "better-scroll";
export default {
props: {
// 显示文字
bottomPullText: {
type: String,
default: "加载中"
},
topPullText: {
type: String,
default: "加载中"
}
},
data() {
return {
wrapScroll: "", //滚动容器对象
isLoading: false,
isLoadingTop: false,
// 记录起始位置,防止上拉加载后回滚到顶;
satrY: 0
};
},
computed: {
scroll(){
return this.wrapScroll
}
},
methods: {
// 上拉加载
uploadMore() {
this.$emit("bottom-method");
this.refresh();
},
downloadMore() {
this.$emit("top-method");
this.refresh();
},
// 加载完毕
finishedUpload() {
this.wrapScroll.finishPullUp();
},
// 刷新组件 (每次内容变化都要调用刷新,否则会出现无法滑动)
refresh() {
if (this.wrapScroll) {
this.wrapScroll.refresh();
}
},
scrollTo(el) {
this.wrapScroll.scrollToElement(el, 300);
this.$emit("bottom-method");
}
},
mounted() {
if (this.wrapScroll) {
// this.refresh()
} else {
this.$nextTick(() => {
this.wrapScroll = new BScroll(this.$refs.wrapper, {
// 是否允许上下滑动(是 true, 否 false)
scrollY: true,
// 是否允许左右滑动(是 true, 否 false)
scrollX: false,
// 上下滑动的起始点
startY: this.satrY,
probeType: 1,
// 是否允许散发点击事件(是 true, 否 false)
click: true,
pullUpLoad: true
});
this.wrapScroll.on("scroll", pos => {
if (this.wrapScroll.maxScrollY - pos.y > 50) {
console.log("会重复触发吗");
this.isLoading = true;
} else {
this.isLoading = false;
}
if (pos.y > 50) {
this.isLoadingTop = true;
} else {
this.isLoadingTop = false;
}
});
this.wrapScroll.on("touchEnd", pos => {
// 上拉距离大于30 发布上拉加载事件
if (this.wrapScroll.maxScrollY - pos.y > 50) {
this.startY = this.wrapScroll.startY;
this.$emit("bottom-method");
setTimeout(() => {
this.refresh();
}, 1000);
}
if (pos.y > 50) {
this.startY = this.wrapScroll.startY;
this.$emit("top-method");
setTimeout(() => {
this.refresh();
}, 1000);
}
});
});
}
}
};
</script>
<style lang="less" scope>
.wrapper {
.loadmore-text-container {
text-align: center;
font-size: 16px;
color: #ccc;
}
.loaddingText {
font-size: 14px;
position: absolute;
width: 100%;
top: -50px;
text-align: center;
line-height: 50px;
// color: #ccc;
}
.loaddingTextBottom {
font-size: 14px;
position: absolute;
width: 100%;
bottom: -50px;
text-align: center;
line-height: 50px;
// color: #ccc;
}
}
</style>
然后我们在页面中引用
<scroll-box>
....中间是滑动区域填充
</scroll-box>
import Scroll from "../../components/scroll";
components: {
"scroll-box": Scroll
},
computed:{
scroller(){
return this.$refs.wrapper.scroll;
},
}
值得一提的是,在页面反复前进后退的时候 ,可能会造成组件计算高度不及时 造成页面无法滑动的情况,这个时候我们需要在activated生命周期中重新手动刷新组件,来完成组件的高度计算
activated() {
this.scroller.refresh()
}
基本上就这么多了,先记录一下
网友评论