better-scroll
安装 npm install better-scroll@next -S
把better-scroll封装成一个组件
<template>
<div class="wrapper" ref="wrapper">
<div class="content">
<slot></slot>
</div>
</div>
</template>
<script>
import BScroll from "@better-scroll/core";
export default {
name: "Scroll",
data() {
return {
scroll: null
};
},
props: {
probeType: {
type: Number,
default: 0
},
pullUpLoad: {
type: Boolean,
default: true
}
},
mounted() {
// 1.初始化scroll
this.scroll = new BScroll(this.$refs.wrapper, {
click: true,
probeType: this.probeType,
pullUpLoad: this.pullUpLoad
});
// 2.监听滚动的位置
if (this.probeType === 2 || this.probeType === 3) {
this.scroll.on("scroll", position => {
this.$emit("scroll", position);
});
}
// 3.监听滚动到底部 上拉事件
if (this.pullUpLoad) {
this.scroll.on("pullingUp", () => {
// console.log('加载更多')
this.$emit("pullingUp");
});
}
},
methods: {
// 封装的滚动到顶部函数
scrollTo(x, y, time = 300) {
// this.scroll && ..是为了判断是否有值
this.scroll && this.scroll.scrollTo(x, y, time);
},
// 加载更多 多次操作
finishPullUp() {
this.scroll && this.scroll.finishPullUp();
},
refresh() {
// console.log('---')
this.scroll && this.scroll.refresh();
},
getScrollY() {
return this.scroll ? this.scroll.y : 0
}
}
};
</script>
<style lang="scss" scoped></style>
使用
<scroll
ref="scroll"
class="scroll"
:probe-type="3"
:pull-up-load="true"
@scroll="contentScroll"
@pullingUp="loadMore"
>
#home {
height: 100vh;
position: relative;
.scroll {
overflow: hidden;
// 方法一:
// height: calc(100% - 93px);
// margin-top: 44px;
// 方法二:
position: absolute;
top: 44px;
bottom: 49px;
left: 0;
right: 0;
}
}
bug(滚动内容高度不确定)
this.scroll.refresh()
与图片加载完成对应起来scrollHeight
事件总线监听(多处调用组件)
媒介main.js中
Vue.prototype.$bus = new Vue()
GoodsListItem.vue:图片加载触发事件总线
<img v-lazy="showImage" @load="imageLoad"/>
imageLoad(){
this.$bus.$emit('itemImageLoad',参数)
}
Home.vue:创建页面就要监听
//created,mounted与$refs.scroll
mounted() {
this.$bus.$on('itemImageLoad',(参数) => {
this.$refs.scroll.refresh()
})
}
刷新过于的频繁(防抖动dobounce,节流throttle)(防止短时间内发送大量请求)
common->util.js
debounce(func,delay){
let timer = null
return function(...args){
if(timer) clearTimeout(timer)
timer = setTimeout(() => {
func.apply(this,args)
},delay)
}
}
// mounted中
const refresh = this.debounce(this.$refs.scroll.refresh,50)
// 版本二
// 对监听事件进行保存(方便做取消监听操作)
itemImgListener = null
this.itemImgListener = () => {
refresh()
}
this.$bus.$on('itemImageLoad',this.itemImgListener)
// 离开home页面(取消监听)(deactivated(){}路由中执行)(destroyed(){}非路由中执行)
this.$bus.$off('itemImageLoad',this.itemImgListener)
// 版本一
this.$bus.$on('itemImageLoad',() => {
refresh()
})