首先需要明确3个定义:
文档高度:整个页面的高度
可视窗口高度:你看到的浏览器可视屏幕高度
滚动条滚动高度: 滚动条下滑过的高度
当 文档高度 = 可视窗口高度 + 滚动条高度 时,滚动条正好到底。
首先在mounted中添加监听:window.addEventListener('scroll', this.scrollFn); // 监听scroll
然后创建3个函数分别获取文档高度、可视窗口高度、滚动条高度:
//文档高度
getScrollTop(){
var scrollTop = 0, bodyScrollTop = 0, documentScrollTop = 0;
if(document.body){
bodyScrollTop = document.body.scrollTop;
}
if(document.documentElement){
documentScrollTop = document.documentElement.scrollTop;
}
scrollTop = (bodyScrollTop - documentScrollTop > 0) ? bodyScrollTop : documentScrollTop;
return scrollTop;
}
//可视窗口高度
getWindowHeight(){
var windowHeight = 0;
if(document.compatMode == "CSS1Compat"){
windowHeight = document.documentElement.clientHeight;
}
else{
windowHeight = document.body.clientHeight;
}
return windowHeight;
}
//滚动条高度
getScrollHeight(){
var scrollHeight = 0, bodyScrollHeight = 0, documentScrollHeight = 0;
if(document.body){
bodyScrollHeight = document.body.scrollHeight;
}
if(document.documentElement){
documentScrollHeight = document.documentElement.scrollHeight;
}
scrollHeight = (bodyScrollHeight - documentScrollHeight > 0) ? bodyScrollHeight : documentScrollHeight;
return scrollHeight;
}
然后在scrollFn函数中判断:
scrollFn(){
if(this.getScrollTop() + this.getWindowHeight() == this.getScrollHeight()){
这里执行动态获取数据的函数
}
}
最后记得销毁监听:
destroyed() {
window.removeEventListener('scroll', this.scrollFn); // 销毁监听
}
如此即可实现滑动加载更多。