鸿蒙开发-分页和加载数据的实现
首先先上预览图
具体实现看代码,思考与实现过程我都写在注释里了
js部分
import prompt from @system.prompt;
const PAGE_NUM=10;
export default {
data: {
arrs:[],
listdata:[],//每次存放10条数据
currentpage:1,
loadtext:"加载更多",
flag:false,
},
onInit(){
for(let i=0;i<50;i++){
this.arrs.push("第"+i+"项");//使用for循环录入数据
}
//使用JavaScript原生api方法 Slice(startnum , endnum)截取十条数据
this.listdata = this.arrs.slice(0,this.currentpage*PAGE_NUM);
},
loadmore(){
this.currentpage ++;
//使用prompt弹出提示信息
prompt.showToast({
message:"加载的是第"+this.currentpage+"页"
})
//总条数/每页条数 = 页数
//使用三元运算符判断具体页数,注意最后一页不满10条数据的情况
let maxSize = this.arrs.length%PAGE_NUM == 0 ?
this.arrs.length/PAGE_NUM:parseInt(this.arrs.length/PAGE_NUM)+1;
console.log("总共"+this.arrs.length+"页");
//if判断是否还有数据未显示,即时更改底部文字信息
if (this.currentpage > maxSize) {
prompt.showToast({
message:"没有更多数据了"
})
this.loadtext = 已经到底了;
this.flag = true;
}
else{
this.listdata = this.arrs.slice(0,this.currentpage*PAGE_NUM)
}
}
}
其他部分就没有太多可说的了
hml部分
<div class="container">
<div class="contentview">
<block for="{
{listdata}}">
<div class="lineview">
<text>{
{$item}}</text>
</div>
</block>
</div>
<div class="operatorview" οnclick="loadmore" disabled="{
{flag}}">
<text>{
{loadtext}}</text>
</div>
</div>
css部分
.container {
display: flex;
flex-direction: column;
width: 100%;
height: 100%;
}
.contentview {
display: flex;
overflow: scroll;
width: 100%;
flex-direction: column;
}
.lineview {
width: 100%;
height: 20%;
border-bottom: 1px solid black;
display: flex;
justify-content: center;
align-items: center;
}
.operatorview {
height: 50vp;
width: 100%;
position: fixed;
bottom: 0;
left: 0;
background-color: aqua;
display: flex;
justify-content: center;
align-items: center;
}
