前端经常会遇到数据分页加载的需求,mint-ui组件为大家提供了loadmore组件
但是我在使用的时候,遇到了一个问题:写好布局和样式以及逻辑之后,我的mt-loadmore标签的头部总是不顶在父元素content的顶部,给了padding也不管用。改了一下午终于找到了原因。
官方文档提供表示,在数据回来之后要执行:
this.$refs.loadmore.onBottomLoaded();
我的问题就是在首次进入页面请求之后,也执行了这一行代码,导致重新计算并滚动了。因此内容顶部隐藏了一部分。
分享我的布局,css,以及逻辑给大家
-
这里遍历展示请求回来的数据
在mounted中执行firstGet函数:
mounted(){
this.firstGet();
},
method:{
firstGet(){
let url = this.baseUrl;
axios.get(url,{
params:{
...
}
}).then(res=>{
//成功之后获取res中的数据以及页码等信息
// this.$refs.loadmore.onBottomLoaded();首次请求或查询第一页不执行,防止头部scroll遮挡问题,这里千万不要加这一行,这是头部遮挡的根源!!!我这里写出来只是为了表示我错在了这一步。这个方法应该只在触发底部的上拉加载更多时使用
//这里的一些变量记得在data里声明,我就不写了
this.curPageNum = res.data.info.curPageNum;
this.maxPageNum = res.data.info.maxPageNum;
if (this.curPageNum >= this.maxPageNum || this.rtnList.length==0) {
this.allLoaded= true;
Toast({
message: "全部数据加载完成",
duration: 1000
});
}else{
this.allLoaded= false;
}
}else{
}
}).catch(err=>{
})
},
loadBottom() {//这是上拉加载更多触发时执行的方法
var that = this;
console.log('触发loadbottom')
if (this.curPageNum>=this.maxPageNum) {
this.allLoaded = true;
Toast({
message: "全部数据加载完成",
duration: 1000
});
this.$refs.loadmore.onBottomLoaded();
return;
}
this.curPageNum++;
let url = this.baseUrl;
axios.get(url,{
params:{
...
}
}).then(res=>{
that.curPageNum = res.data.info.curPageNum;
that.maxPageNum = res.data.info.maxPageNum;
if (that.curPageNum>=that.maxPageNum || this.rtnList.length==0) {
that.allLoaded= true;
Toast("全部数据加载完成");
}else{
that.allLoaded= false;
}
that.$refs.loadmore.onBottomLoaded();//这里数据回调成功之后要重新获取mt-loadmore内部的高度
}else{
that.nodata =true;
}
}).catch(err=>{
that.nodata =true;
})
}
}
其实我的firstGet方法和bottomLoaded方法是很像的,区别只在于第一次请求,或者说请求回来第一页数据的时候,不要执行this.$refs.loadmore.onBottomLoaded();他的作用是重新计算获取了新数据的div的高度,并向上滚动一点点让数据漏出来。如果首次请求就重新计算,就会让数据上移,从而被遮挡。那父级元素的padding也无法拯救他了~