记录:滚轮触顶后,加载数据,重新计算滚轮所在位置。
先看效果:

示例代码
scrollHeight:返回元素整体的高度,包括由于overflow溢出而在屏幕上不可见的内容。
第一步:
首先在mounted中监听滚动条事件,触发handleScroll函数
此处setTimeout为模拟异步请求数据
你们应该在异步请求数据之后,nextTick之后获取scrollHeight。
// 示例代码
mounted(){
window.addEventListener('scroll', this.handleScroll,true)
setTimeout(()=>{
this.lastScrollHeight = document.documentElement.scrollHeight;
console.log(document.documentElement.scrollHeight,"lastScrollHeight")
},1000)
},
// 实际场景
getApi().then((res) => {
this.count = res.data;
this.$nextTick(() => {
// 获取scrollHeight
...
this.lastScrollHeight = document.documentElement.scrollHeight;
console.log(document.documentElement.scrollHeight,"lastScrollHeight")
})
})
坑一:如果你获取的数据中有图片, 可以使用图片onLoad(图片加载成功)事件,写一个promise,等待所有图片load成功后,再获取scrollHeight。
在我的示例中,每个盒子高度为50+margin10 = 60; 总高度60 * 20 = 1200;

第二步:
滚动鼠标滚轮,触发handleScroll事件
如果 小于等于 0 为到顶了~~
此时继续异步请求数据,操作同上。
// 示例代码
setTimeout(()=>{
var scrollTopCount = document.documentElement.scrollHeight - this.lastScrollHeight;
document.querySelector('html').scrollTop = scrollTopCount;
this.lastScrollHeight = document.documentElement.scrollHeight;
},1000)
// 实际场景
getApi.then(()=>{
var scrollTopCount = document.documentElement.scrollHeight - this.lastScrollHeight;
document.querySelector('html').scrollTop = scrollTopCount;
this.lastScrollHeight = document.documentElement.scrollHeight;
},1000)
此时获取的scrollHeight为添加数据之后元素的高度 减去 上一次元素的高度 = 需滚动的高度
就o壳了。
以下为全部示例代码。
<script>
import { nextTick } from 'vue';
export default {
data() {
return {
count:[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20],
lastScrollHeight:0,
}
},
mounted(){
window.addEventListener('scroll', this.handleScroll,true)
setTimeout(()=>{
this.lastScrollHeight = document.documentElement.scrollHeight;
console.log(document.documentElement.scrollHeight,"lastScrollHeight")
},1000)
},
methods:{
handleScroll(){
var scrollTop = document.documentElement.scrollTop;
if(scrollTop === 0){
console.log("到顶了-----------------------------------")
this.count.unshift(1,2);
setTimeout(()=>{
var scrollTopCount = document.documentElement.scrollHeight - this.lastScrollHeight;
document.querySelector('html').scrollTop = scrollTopCount;
this.lastScrollHeight = document.documentElement.scrollHeight;
},1000)
}
}
}
}
</script>
<template>
<div class="list-item" v-for="item in count" :key="item">
{{item}}
</div>
</template>
<style>
*{
margin: 0;
padding:0;
}
.list-item{
margin-top: 10px;
display: flex;
align-items: center;
justify-content: center;
height: 50px;
background: pink;
color: blue;}
</style>
Vue组件滚动事件处理与数据动态加载策略,
4727

被折叠的 条评论
为什么被折叠?



