触底加载更多(原理)
理解
1.使用api分别获取
滚动高度(document.documentElement.scrollTop)
可视区域/屏幕高度(document.documentElement.clientHeight)
页面高度(document.documentElement.scrollHeight)
2.原理 :If(滚动高度 + 可视区域 >= 页面高度){ do something函数}
vue中的应用
1.用事件监听,监听你要执行的事件
window.addEventListener(‘scroll’, 你要执行的事件)
2.取消事件监听,监听你要执行的事件
window.removeEventListener(‘scroll’, 你要执行的事件,false)
一定要取消事件监听!不然你执行完这个事件它也会到其他页面继续执行这个事件。
例子
data: function() {
return {
group:[], //返回数据
page:1, //加载页数
};
},
mounted() {
//事件监听
window.addEventListener('scroll', this.listenBottomOut)
//预先加载一遍
getGroulp(1).then(res =>{
this.$set(this,"group",res.data)
})
},
//vue 的生命周期钩子函数
methods: {
//触底触发函数
listenBottomOut () {
let scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
let clientHeight = document.documentElement.clientHeight;
let scrollHeight = document.documentElement.scrollHeight;
if (scrollTop + clientHeight >= scrollHeight) {
if(this.group.length === 10){
getGroulp(this.page + 1).then(res =>{
var groups = this.group.concat(res.data)
this.$set(this,"group",groups)
})
}
}
},
},
//vue 的生命周期钩子函数
destroyed(){
//离开页面取消监听
window.removeEventListener('scroll', this.listenBottomOut,false)
}