基于Vue2实现滚动过程中数据懒加载
以下为实现滚动懒加载的过程:
1、在data
对象中定义了items
数组,用于存放已加载的item
,loading
状态,当前页数page
,每页数量pageSize
,以及距离底部的阈值threshold
。
2、在mounted
钩子函数中,首次加载数据调用loadMore
方法,并绑定滚动事件。
3、loadMore
方法被调用后,将loading
状态设为true
,模拟异步加载数据,往items
数组中push
每次固定数量的item
,再将loading
状态设为false
,page
加1。
4、handleScroll
方法监听滚动事件,获取当前滚动位置scrollTop
,视口高度windowHeight
,以及文档总高度scrollHeight
。如果文档总高度 - (滚动位置 + 视口高度)
小于阈值threshold
,则触发loadMore
方法加载更多数据。
5、beforeDestroy
钩子函数解绑滚动事件。
以下代码把
loadMore()
函数修改为真正的http请求即可,下面代码中使用settimeout
模拟生成数据
<template><div style="height: 100px"><div v-for="item in items" :key="item.id" class="item">{{ item.text }}</div><div v-if="loading">Loading...</div></div>
</template><script>
import { throttle } from 'lodash'
export default {data() {return {items: [], // 用于存放已加载的 itemloading: false, // 控制是否展示 loadingpage: 1, // 当前页数pageSize: 5, // 每页数量threshold: 100, // 距离底部多少像素时触发加载};},mounted() {this.loadMore(); // 首次加载数据window.addEventListener("scroll", throttle(this.handleScroll, 1000)); // 绑定滚动事件},methods: {loadMore() {this.loading = true; // 开启 loading 状态// 模拟异步加载数据setTimeout(() => {for (let i = 0; i < this.pageSize; i++) {this.items.push({id: this.items.length + 1,text: `Item ${this.items.length + 1}`,});}this.loading = false; // 关闭 loading 状态this.page++;}, 1000);},handleScroll() {const scrollTop =document.documentElement.scrollTop || document.body.scrollTop; // 获取当前滚动位置const windowHeight = window.innerHeight; // 获取视口高度const scrollHeight =document.documentElement.scrollHeight || document.body.scrollHeight; // 获取文档总高度if (scrollHeight - (scrollTop + windowHeight) < this.threshold) {// 判断是否已滚动到底部this.loadMore(); // 触发加载更多}},},beforeDestroy() {window.removeEventListener("scroll", throttle(this.handleScroll, 1000)); // 解绑滚动事件},
};
</script>
<style lang="less" scoped>
.item {height: 200px;
}
</style>
scrollTop
表示当前滚动条的位置,即已经滚动过的高度。
window.innerHeight
表示浏览器视口的高度。
scrollHeight
表示当前文档的总高度,包括了未显示出来的部分。