当我们需要实现无限加载的时候,即实现瀑布流的功能的时候,核心就是监听页面的滚动事件,当滚动触底的时候去请求加载数据,既可以实现无限加载下拉。
监听scroll事件
因为组件内部 是通过数据渲染出的列表 考虑vue渲染规则 需要在元素渲染后执行scroll监听 否则获取不到对应dom节点,所以需要配合使用 $nextTick()。
<template>
<div ref="content"></div>
</template>
<script>
created() {
this.$nextTick(()=>{
this.$refs.content.addEventListener('scroll', this.isScrollBottom)
})
},
</script>
2
3
4
5
6
7
8
9
10
添加节流
由于监听滚动事件,只要滚动事件被触发就会执行,但是实际上我们不要在滚动过程中的结果,而是最终滚动停止的位置去触发事件,这个时候就可以添加js节流来实现,避免无效的事件处罚来提升性能。
function throttle (fn, wait) {
let timer = null;
return function (...args) {
let context = this
if (timer) {
clearTimeout(timer);
timer = null;
}
timer = setTimeout(function () {
fn.apply(context, args)
}, wait)
}
}
this.containerScrollFn = this.throttle(this.[方法], 200);
this.$nextTick(()=>{
this.$refs.content.addEventListener('scroll', this.containerScrollFn);
})
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
滚动至底部判断
isScrollBottom() {
const container = this.$refs.content;
var scrollTop = container.scrollTop;
var windowHeight = container.clientHeight;
var scrollHeight = container.scrollHeight;
if(scrollTop+windowHeight == scrollHeight){
this.getBroadcast(this.theNum);
this.isBottom = true; // 滚动至底部
//添加需要在触底时实现的功能函数
}else{
this.isBottom = false;
}
},
2
3
4
5
6
7
8
9
10
11
12
13