vue项目、h5项目 实现向上翻页功能--类微信聊天信息
实现技术难点:
1:监听已经到顶部
2:加载完数据需要定位到原先位置
-- 记录新增数据前、后的可滚动高度,
-- 重点:移动的距离= 数据新增加载完后总高度 - 新增前总高度
如下使用vue项目:
<template>
<div id="app">
<div ref="container" class="container" @scroll="scroll">
<div class="loading">加载更多...</div>
<div v-for="(item, index) in list" :key="index" class="item">{{ item }}</div>
</div>
</div>
</template>
<script>
export default {
components: {
},
data() {
return {
scrollHeight: 0,
list: [],
loadText: '加载中...',
isLoading: false,
pageSize: 20,
pageNum: 1,
};
},
mounted() {
this.initData();
// 首次渲染后获取scrollHeight并滑动到底部。
this.$nextTick(() => {
this.scrollHeight = this.$refs.container.scrollHeight;
this.$refs.container.scrollTo({ top: this.scrollHeight });
});
},
methods: {
// 初始数据
initData() {
const arr = [];
for (let i = 30; i > 0; i--) {
arr.unshift('第' + this.pageNum + '页:' + i);
}
this.pageNum++;
this.list = [...arr, ...this.list];
this.isLoading = false;
},
// 滚动
scroll(e) {
// 滑到顶部时触发下次数据加载
if (e.target.scrollTop == 0 && !this.isLoading) {
this.isLoading = true;
// 记录高度
this.scrollHeight = this.$refs.container.scrollHeight;
// 模拟延迟时间获取数据
setTimeout(() => {
this.initData();
// 定位
this.$nextTick(() => {
this.$refs.container.scrollTop = this.$refs.container.scrollHeight - this.scrollHeight;
});
}, 2000);
}
}
}
};
</script>
<style lang="less" scoped>
.container {
width: 100%;
height: 1500px;
overflow: auto;
}
.loading{
height: 70px;
line-height: 70px;
text-align: center;
}
.item {
height: 100px;
line-height: 100px;
text-align: center;
border-top: 1px solid #aaa;
}
.container .item:last-child {
border-bottom: 1px solid #aaa;
}
</style>