vue.js上拉加载
注意事项:
1.overflow属性会导致滚动事件失效
2.连续下拉会导致数据加载时出现问题,给了1s的延迟
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>demo</title>
</head>
<style>
* {
margin: 0;
padding: 0;
}
[v-cloak] {
display: none !important;
}
html,
body {
width: 100%;
height: 100%;
/* overflow-x: hidden; */
/* overflow: scroll; */
}
.empty {
height: 800px;
}
</style>
<body>
<div id="demo" v-cloak>
<div class="empty"></div>
<ul>
<li v-for="item in lists">item</li>
</ul>
<h2>{{paging.loadingMessage}}</h2>
</div>
</body>
<script src="vue.js"></script>
<script>
var vum = new Vue({
el: "#demo",
data: {
paging: {
PageIndex: 1,
PageSize: 10,
isTrue: false,
showLoading: false,
loadingMessage: "上拉加载更多~"
}, //分页
lists: []
},
methods: {
handleScroll() {
var that = this;
//判断滚动到底部
if (document.body.scrollTop >= document.body.clientHeight - window.screen.availHeight) { //滚动高度>=页面高度-屏幕高度
if (that.paging.isTrue) {
setTimeout(function() {
that.paging.PageIndex++;
that.paging.showLoading = true;
that.paging.loadingMessage = "正在加载中~";
that.getList();
}, 1000); //防止连续下拉
that.paging.isTrue = false;
}
}
},
getList() {
var that = this;
let datas = [];
for (let i = 0; i < 10; i++) {
datas.push({
i
})
}
that.paging.PageIndex == 1 ? that.lists = datas : that.lists = that.lists.concat(datas);
if (datas.length < that.paging.PageSize) {
that.paging.isTrue = false;
that.paging.loadingMessage = "暂时没有更多消息了哦~";
} else {
that.paging.isTrue = true;
that.paging.loadingMessage = "上拉加载更多~";
}
}
},
mounted() {
//监听滚动
window.addEventListener('scroll', () => {
this.handleScroll();
});
//初始加载数据
setTimeout(() => {
this.getList();
}, 1000);
}
})
</script>
</html>