今天让我们来写一个h5的触底翻页加载数据,还是挺简单的
我们先写一个触底执行事件的demo,首先要有一个盒子给他添加一个滚动监听事件
<div @scroll="handleScroll" style="height: 200px; overflow-y: scroll;">
<!-- 滚动列表 -->
<div class="list" v-for="item in cardList">
<!-- 列表内容 -->
</div>
</div>
然后我们来写滚动监听的函数
handleScroll(e) {
// 距离顶部的距离
const scrollTop = e.target.scrollTop;
// 可视区的高度
const windowHeight = e.target.clientHeight;
// 滚动条的总高度
const scrollHeight = e.target.scrollHeight;
// 当滚动条滚动到底部
if (scrollTop + windowHeight == scrollHeight) {
//这里写触底要执行的事件
console.log("到底啦")
}
这一次我们再来加一个loading来增加用户的体验感,这里就不用其他的组件了,使用时可以根据自己的需要切换成其他的loading组件,完整代码如下:
<div @scroll="handleScroll" style="height: 200px; overflow-y: scroll;">
<!-- 滚动列表 -->
<div class="list" v-for="item in cardList">
<!-- 列表内容 -->
</div>
<div v-if="isLoading" class="loading">Loading...</div>
</div>
<script>
export default {
data() {
return {
isLoading: false, // 初始状态下加载状态为 false
cardList: [],
page: 1,
total: 0,
limit: 5
};
},
methods: {
handleScroll(e) {
const scrollTop = e.target.scrollTop;
const windowHeight = e.target.clientHeight;
const scrollHeight = e.target.scrollHeight;
// 当滚动条滚动到底部
if (scrollTop + windowHeight === scrollHeight && this.cardList.length < this.total) {
this.isLoading = true; // 设置加载状态为 true,显示 loading 提示
console.log("到底啦");
// 模拟数据加载,实际项目中应替换为真实的数据请求逻辑
setTimeout(() => {
this.isLoading = false; // 数据加载完毕后,将加载状态设置为 false,隐藏 loading 提示
this.page++
// 这里可以进行下一页数据的获取与渲染
this.getCardList()
}, 2000); // 假设数据加载需要2秒时间
}
},
},
//这个是获取数据的方法,方法内部具体的翻页方法这里就不具体写了
getCardList() {
}
};
</script>
<style>
.loading {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
z-index: 999;
text-align: center;
}
</style>
这个是vue2版本,vue3同理