一、关于scorll事件应用于在列表数据加载
1、我们首先要认识关于浏览器页面的滚动原理和页面内容滚动的原理
粗略展示的图,画的一般,见谅见谅,下面简单的描述一下。
简略布局
<div class='equipment-search'>
<van-search
v-model="search"
show-action
clearable
placeholder="请输入搜索内容"
@search="onSearch"
>
<template #action>
<div
@click="onSearch"
class="search-name"
>搜索</div>
</template>
</van-search>
</div>
过程处理
handleScroll () {
// 变量scrollTop是滚动条滚动时,距离顶部的距离
const scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
// 变量windowHeight是可视区的高度
const windowHeight = document.documentElement.clientHeight || document.body.clientHeight;
// 变量scrollHeight是滚动条的总高度
const scrollHeight = document.documentElement.scrollHeight || document.body.scrollHeight;
// 滚动条到底部的条件(距底部20px时触发加载)
if (scrollTop + windowHeight > scrollHeight - 20 && !this.isAchiveBottom && !this.showData) {
this.isAchiveBottom = true;
const length = this.equipmentList.length;
if (length === this.total) {
this.isAchiveBottom = false;
this.$toast('没有更多数据了');
this.showData = true;
return false;
} else {
// 延时触发数据加载
setTimeout(() => {
this.pageParams.page++;
this.getNewList();
this.isAchiveBottom = false;
}, 500);
}
}
}
对于事件的生命周期的处理
mounted () {
window.addEventListener('scroll', this.handleScroll, true);
},
destroyed () {
window.removeEventListener('scroll', this.handleScroll, false);
},
备注:在window挂监听事件,这个需要离开的时候销毁,不然会影响到其他页面的滚动加载;